How to get the parent document ID of a subcollection when using CollectionGroup queries?
356
doc.id
returns the underlying document ID. You need to first get the current DocumentReference
(doc1
, doc2
), using that get CollectionReference
(subC
) and then get its parent which is your document1
and document2
.
So, you need this:
var col = FirebaseFirestore.instance.collectionGroup('subC').where('foo', isEqualTo: 'bar');
var snapshot = await col.get();
for (var doc in snapshot.docs) {
print(doc.reference.parent.parent?.id); // Prints document1, document2
}
Author by
iDecode
When developers want to hide something from you, they put it in docs.
Updated on December 31, 2022Comments
-
iDecode over 1 year
I'm using collection group query but I'm unable to get the parent document ID.
collection document1 subC doc1 document2 subC doc2
On running a query I want to get the name of parent document, i.e.
document1
,document2
, etc but it returns medoc1
anddoc2
. This is my query:var col = FirebaseFirestore.instance.collectionGroup('subC').where('foo', isEqualTo: 'bar'); var snapshot = await col.get(); for (var doc in snapshot.docs) { print(doc.id); // Prints doc1, doc2 }