In Firestore, I have added a single document in a subcollection, I don't know its id because it was added in the past, but I know its path. How to get its id ? Should I save its id at the creation?
Thank you
I don't know its id because it was added in the past, but I know its
path.
If with "I know its path" you refer to the Document path, then the Document ID is the last element of the path, in which elements are separated by a slash. For example rootCollectionName/parentDocId/parentCollectionName/docId.
If with "I know its path" you refer to the path of the subcollection, then you could query the subcollection and take the first document, since there is a single doc in the collection.
For example with Dart:
QuerySnapshot querySnapshot = await Firestore.instance.collection("rootCollectionName/parentDocId/parentCollectionName").get();
var documentID = querySnapshot.docs[0].id;
Related
After getting a snapshot for a particular document in a subcollection, I would like to get the associated data to the root document which it belongs to.
For example, there is a collection restaurants and each one has a products subcollection.
After searching for a particular product of a restaurant, how can I get the restaurant data which the product belongs to? Do I need to make another search or how can I get it from the product snapshot?
QuerySnapshot snapshot = await FirebaseFirestore.instance
.collectionGroup('products').get();
QueryDocumentSnapshot product = snapshot.docs.elementAt(0);
There's actually a very easy way to do this, and it takes advantage of the ref.path of the document. You can split the ref.path string into it's component sections - remember, it's the full "/" separated path to the document, so for example:
restaurants/{restaurantId}/products/{productId}
topCollection/{topdocumentId}/nextCollection/{nextDocumentId}/.../bottomCollection/{bottomDocumentId}
Clearly, the first two segments are the path to the "parent" document - regardless of the depth of the tree (I happen to have a very deep tree structure). You can then fetch the "top parent":
db.collection(topCollection).doc(topdocumentId).get()
To find the parent/restaurant document for product, you'll want to walk up the reference/parent chain:
var restaurantRef = product.reference.parent.parent;
You will still need to get that document with:
var restaurantDoc = await restaurantRef.get();
I have a nested collection in firestore that I want to make a query from it.
As you can see the first collection called 'businessUsers' and the nested one called 'campaigns',
If I make a query for a field in the 'businessUsers' it's working OK:
return FirebaseFirestore.instance.collection("businessUsers").where('xxx',
isEqualTo:filterBusinessResult ).snapshots().map(_businessListFromSnapshot);
but how can I make a query to 'campaigns' collection field?
I tried
return FirebaseFirestore.instance.collection("businessUsers").doc().collection("campaigns").where('campaignCategory', isEqualTo:filterBusinessResult ).snapshots()
.map(_businessListFromSnapshot);
but it wont work.
Its important to note, that I need all the data with 'campaignCategory' == filterBusinessResult
any idea?
It depends on whether you want to query a specific user's campaigns, or the campaigns of all users together.
If you want to query the campaigns of a specific user, you need to query under their document:
FirebaseFirestore.instance
.collection("businessUsers").doc("your user ID").
.collection("campaigns")
.where('campaignCategory', isEqualTo:filterBusinessResult)
So you have to know the ID of the businessUsers document here.
If you want to query across all campaigns subcollections are once, that is known as a collection group query and would look like this:
FirebaseFirestore.instance
.collectionGroup("campaigns")
.where('campaignCategory', isEqualTo:filterBusinessResult)
The results are going to documents from the campaigns collection only, but you can look up the parent document reference for each DocumentSnapshot with docSnapshot.reference.parent.parent.
When querying something, .doc() requires the id of the document you're trying to get. So it's failing because it doesn't know which document in the businessUsers collection you're trying to fetch a subcollection on. You probably want to use a .collectionGroup() query here. They let you query all subcollections at once (see documentation here). With FlutterFire specifically, it's going to be something like:
var snapshots = FirebaseFirestore.instance.collectionGroup("campaigns")
.where("campaignCategory", isEqualTo: filterBusinessResult)
.snapshots();
Guys how can i retrieve a specific document from QuerySnapshot.docs?
I once get all documents of a collection.
And after some code, i want to get a document by its ID from that collection.
I want to get that document specifically from this QuerySnapshot since i don't want to be messed with await later in my code.
So if i can get all documents all at once, why would i get every document one by one later with async call which would waste my time?
The thing would look like this:
QuerySnapshot usersSnapshot = await FirebaseFirestore.instance.collection("users").get();
//
//some code
//
DocumentSnapshot userDoc = usersSnapshot.docs.doc("user12345");
I want to get document with id user12345.
Is there any function like this .doc(ID) that i can apply on QuerySnapshot??
No, there is no such method on QuerySnapshot. You have to locate the document you want by iterating the results of the query in the docs property, and check each DocumentSnapshot for the ID you're looking for.
If you want to make that easier for yourself for repeated lookups, you can iterate the docs list, and build a Map of document snapshots keyed by the ID. Query the Map for each document you want.
I am trying to create a document and collection following each other
with this reference
CollectionReference att = FirebaseFirestore.instance
.collection('attendance/$_currentClass/pieces');
but when it is created it is shown like that image below
and i can't see documents that has name of "_currentClass" variable.
If we create create it by ourselves it creates properly.
Here top one was created by me and bottom one created inside flutter
What am i doing wrong?
Based on your path your CollectionReference to this subcollection is:
CollectionReference att = FirebaseFirestore.instance
.collection('attendance')
.doc(_currentClass)
.collection('pieces');
Document, you are pointing with italic font does not exist, it was deleted, but before that it had a collection, and pointing that documents on that subcollection were not deleted and they still exist.If you create documents with sub-documents and then delete the top level document from an SDK, the delete is not recursive. So while the top-level document is gone, its sub-documents remain.
Since there is no document anymore, the document itself will not show up in query results. If you need to find this document in query results, you'll want to create an empty document as a workaround.
Context: In the frontend the user can enter of delete dates for availability. This is how I added a date:
Firestore.instance.collection('availableDates').add({
'availableDates':date});
But I also need to delete a document from a collection in Firestore. I don't know the document id but I know the the field value which is unique. How would I go about deleting the document if I know the field value within the document. Here is a screen shot of firestore:
You can fetch the document first and then delete the document. For example:
var collection = FirebaseFirestore.instance.collection('countries');
var snapshot = await collection.where('city', isEqualTo: 'CA').get();
await snapshot.docs.first.reference.delete();
If anyone is confused after the update of why this code is not working please refer to this one. Update of March 21st, 2021.
refUser.where("city", isEqualTo: "CA").get().then((snapshot){
snapshot.docs.first.reference.delete();
});
I took a bit of time myself to get around this but if it helps even a single person stuck like me then it's all worth it. :)