Reputation: 1134
I wanted to know if it's possible to refer a subcollection, once a document is queried? I understand that .get() returns a promise and we write a function on it to get the document. But is it possible to use the document queried to access that subcollection, without having to get document's id and using it inside .doc()?
Upvotes: 0
Views: 86
Reputation: 83093
No, this is not possible without issuing a new query. There is no method that allows that for a DocumentSnapshot
.
To illustrate that, let's imagine you get a city document through a query (which you know returns only one doc):
var citiesRef = db.collection("cities");
citiesRef.where("name", "==", "Brussels").get()
.then(function(querySnapshot) {
if (!querySnapshot.empty) {
var doc = querySnapshot.docs[0];
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);
});
and you know that this doc has a sub-collection for restaurants in this city. If you want to get this collection you would need to do:
var citiesRef = db.collection("cities");
citiesRef.where("name", "==", "Brussels").get()
.then(function(querySnapshot) {
if (!querySnapshot.empty) {
var doc = querySnapshot.docs[0];
var restaurantsCollRef = citiesRef.doc(doc.id).collection("restaurants");
return restaurantsCollRef.get();
} else {
throw new Error("No such document!");
}
})
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
})
}).catch(function(error) {
console.log("Error getting document:", error);
});
One point to be noted is that actually a document and one of its sub-collection are not, from a technical perspective, relating to each other.
Let's take an example: Imagine a doc1
document under the col1
collection
col1/doc1/
and another one subDoc1
under the subCol1
(sub-)collection
col1/doc1/subCol1/subDoc1
Actually, they just share a part of their path but nothing else. One side effect of this is that if you delete a document, its sub-collection(s) still exist.
Upvotes: 1