1

I need help with something.

I have 2 collections on my project, one is called products and another called stores.

One product can belong to many stores, so to make the app more “performatic”, I’m duplicating the selected product information into a sub-collection of stores, in this case stores > products.

My idea is to create a cloud-function that will watch for any updates on any product and then reflect those changes on the stores > products sub-collection by updating the values.

I’m already saving it with the same ID. So for example, the productID 1 under the products collection will have the same id under the stores > products sub-collection.

My question is, how can I query only the products sub-collection? Is this possible?

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
MrRobot
  • 1,001
  • 1
  • 14
  • 34

2 Answers2

2

It depends what do you exactly want to query.

If you want to query only ONE specific product document within the products sub-collection of ONE given store document you would do as follows:

var docRef = db.collection("stores").doc(storeId).collection("products").doc(productId)

docRef.get().then(function(doc) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
}).catch(function(error) {
    console.log("Error getting document:", error);
});

If you want to query the products sub-collection of ONE given store (getting all the products docs within this sub-collection) you would do as follows:

db.collection("stores").doc(storeId).collection("products").get()
  .then(function(querySnapshot) {
     //....
  })
  .catch(function(error) {
     //....
  });

If you want to query the products sub-collections of ALL the stores, you would use a Collection Group Query, as follows:

var productsCollGroup = db.collectionGroup('products');

productsCollGroup.get()
.then(function (querySnapshot) {
     //....
})
.catch(function(error) {
     //....
});
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • 1
    Hey thanks. If I run the `collectionGroup` wouldn't that also catch the main **Products** collection? Would that be the case for me to change the name of that sub-collections? – MrRobot Sep 03 '19 at 14:57
0

You can check the thread on this link [1], specifically to your question you can check this answer [2].

For example they mention have an array of documents and they provide the answer of how to search for an specific document within a collection.

[1] Firestore query subcollections

[2] https://stackoverflow.com/a/46585748/9054282

Harif Velarde
  • 733
  • 5
  • 10