I have tasks subcollection for every user, How can I delete tasks ,
CollectionReference users = FirebaseFirestore.instance.collection('users');
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<void> deleteTask() {
return users
.doc(user.uid)
.collection('Tasks').delete() ?? ??
.then((value) => print("Tasks Deleted"))
.catchError((error) => print("Failed to delete task: $error"));
}
To delete all documents in collection or subcollection with Cloud Firestore, you can use the delete method iterating on a DocumentReference:
CollectionReference users = FirebaseFirestore.instance.collection('users');
Future<void> deleteAllTaskDocs() {
return users
.doc(user.uid)
.collection('Tasks')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
doc.reference.delete();
});
});
}
Keep in mind that:
There is no operation that atomically deletes a collection.
Deleting a document does not delete the documents in its subcollections.
If your documents have dynamic subcollections, it can be hard to know what data to delete for a given path.
Deleting a collection of more than 500 documents requires multiple batched write operations or hundreds of single deletes.
Related
User? user = FirebaseAuth.instance.currentUser;
late Stream<QuerySnapshot<Map<String, dynamic>>> stream = FirebaseFirestore
.instance
.collection('contents')
.doc(user!.uid)
.collection('content')
.snapshots();
This user!.uid is uid of the current user. I need to get uid of all the users.
So I am trying to make a chat app with cloud Firestore and I don't how to delete a document by timestamp.
This is currently how I delete a document.but when I tried it deletes all the document:
onLongPress: () async {
await FirebaseFirestore.instance
.collection('messages')
.doc(
groupChatId)
.collection(
groupChatId)
.orderBy("timestamp",descending: true).get().then((value) => {
for(DocumentSnapshot ds in value.docs){
ds.reference.delete()
}
});
},
try this code:
await FirebaseFirestore.instance
.collection('messages')
.doc(
groupChatId)
.collection(
groupChatId)
.where("timestamp", isLessThan: DateTime.now().microsecondsSinceEpoch-TheNumberOfMicrosencundenTheDocumentCanBeOld).get().then((value) => {
for(DocumentSnapshot ds in value.docs){
ds.reference.delete()
}
});
I am trying to get users name but Flutter gives this error:
The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
Method:
String getUserNameFromUID(String uid) {
FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: uid)
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
return doc["name"];
});
});
}
How can I solve my problem? if I add return 0 to end of the method it always gives 0.
It always gives 0.(I do not want 0, I want get user name from uid)
String getUserNameFromUID(String uid) {
FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: uid)
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
return doc["name"];
});
});
return "0";
}
EDIT: I need a String solution, not Future. The method should return String...
Because my UI is not future builder. Isn't there any way to return one data as String in Firestore database?
First your function should return a Future<String> since it relies on firestore's get wich also returns a future. Also docs is a list, you have to return just one. The first one i guess. In the UI just use a FutureBuilder
Future<String> getUserNameFromUID(String uid) async {
final snapshot = await FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: uid)
.get();
return snapshot.docs.first['name'];
}
Since you can't use FutureBuilder. An ugly alternative is to pass a callback to getUserNameFromUID and call setState from there.
void getUserNameFromUID(String uid, Function (String name) onData) {
final snapshot = await FirebaseFirestore.instance
.collection('users')
.where('uid', isEqualTo: uid)
.get().then((s) => onData(s.docs.first['name']));
}
On your UI
...
getUserNameFromUID(uid, (String name){
setState(()=> name = name);
});
From your last comment just inherit from StatefulWidget. And call the function from inside.
#override
void initState() {
getUserNameFromUID(uid);
}
If you had special requirements about not being able to modify the UI, you should mention that as it conditions the way to use the backend services.
FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(value.data());
});
});
});
print(info.toString());
}
I am trying to build a Flutter application using Firestore.My firestore has two collections namely users and friends.Collection users contains documents with locations,names and Collection friends contains documents which each have a subcollection friends that store the Unique IDs of "users" who are friends. This is the output when I execute the above function
I/flutter ( 7773): hello eyHBWGrNoxSMe8cQUqWC
I/flutter ( 7773): []
I/flutter ( 7773): lalala{loc: Instance of 'GeoPoint', dname: hamza ansari}
PROBLEM: The data is not getting stored into the list 'info'. Any help with this would be appreciated :D
.Here is a photo of the friends collection.
And here is a photo of the users collection.
Would really love it if someone could help me out here :)
You can access the documents by snapshot.data.documents then you can get document Id like this
var doc= snapshot.data.documents;
var docId=doc[index].documentID
FirebaseFirestore.instance
.collection('dishes')
.doc(docId)
.collection('ingredients')
.snapshots(),
i think the problem is that you are simply not returning anything in your Future.
try this
FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(value.data());
});
});
});
return info ;
}
The problem seems to be with the conversion of the subcollection to a list. Try the following:
FirebaseFirestore _firestore = FirebaseFirestore.instance;
CollectionReference _userRef = FirebaseFirestore.instance.collection('users');
Future getFriends() async {
List<Map> info = [];
await _firestore
.collection('friends')
.doc('lUb3VEzLQsqxxEhwO3nU')
.collection('friends')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((element) async {
print("hello " + element.id.toString());
await _userRef.doc(element.id).get().then((value) {
print("lalala" + value.data().toString());
info.add(Map(Map.fromMap(value.data())));
});
});
});
print(info.toString());
}
How to read subcollection from flutter firestore. I am using cloud_firestore. I am successfully adding data into firestore but couldn't retrieve it(tried and failed).
I want to retrieve subCollection called product Firestore collection
I tried this I don't have the document ID Because it generated automatically from firestore :
Stream<QuerySnapshot> loadorderdetails(String uid) {
return FirebaseFirestore.instance
.collection('Users/$userid/Orders')
.doc()
.collection("Products")
.where('uid', isEqualTo: uid)
.snapshots();
}
You should try this
FirebaseFirestore.instance.collection("Users/$userid/Orders ").get().then((querySnapshot) {
querySnapshot.docs.forEach((result) {
FirebaseFirestore.instance
.collection("Users/$userid/Orders")
.doc(result.id)
.get()
.then((querySnapshot) {
//print data
});
});
});
});