Reputation: 323
It this possible to do? After some research, I couldn't find a way to do it.
My "workaround" is to get all subCollection documents first, then retrieve their parent keys and retrieve again. But I believe there is a better way to do it.
let subDocs = await firestoreDb.collectionGroup('sub_collections').get()
let parentDocKeys = {};
subDocs.docs.forEach(async (element) => {
parentDocKeys[element.ref.parent.parent.id] = 1;
});
let result = await firestoreDb.collection('parentCollection').where(firestore.FieldPath.documentId(), 'in', Object.keys(parentDocKeys)).get();
return res.send(result.docs.map(x=>x.data()));
Upvotes: 3
Views: 1148
Reputation: 600071
Firestore queries can only filter documents based on data in the document itself. There is no way to check data in any other documents, neither in the same collection, nor in other (sub)collections.
This means that it is not possible to retrieve only documents for which a subcollection exists without changing the data in the parent document. For example, if you update a field (say hasSubcollectionBla
) in the parent document each time you add/remove to the subcollection, you can filter on the value of that field.
What you do with this is making the writing of data more complex, so that the read/query becomes easier and more scalable. This is a common trade-off when using NoSQL databases, such as Firestore.
Upvotes: 5