Reputation: 4253
I've a collection called users
, inside each document's users have a collection called monthlies
and I want get it.
This is the structure:
At now, I tried get it using:
var getUsers = async function() {
var db = firebase.firestore()
var users = await firebase
.firestore()
.collection("users")
.get();
return users
}
var getMonthlyByUserId = async function () {
var users = await getUsers()
users.forEach(element => {
var monthlies = element.collection('monthlies').get()
console.log(monthlies.docs.map(doc => doc.data()))
})
}
But it prints nothing. The goal is iterate of all documents' monthlies of the collection.
Upvotes: 3
Views: 4407
Reputation: 83191
In addition to the problem that Doug pointed out (you need to use the ref
property of the QueryDocumentSnapshot
), you need to take into account that the get()
method is asynchronous.
So doing
users.forEach(snapshot => {
var monthlies = snapshot.ref.collection('monthlies').get()
console.log(monthlies.docs.map(doc => doc.data()))
})
will not work.
If you cannot use a collection group query (for example, let's imagine that your getUsers()
function only returns a subset of all the users, e.g. all users of a given country) you could use Promise.all()
as follows:
var getMonthlyByUserId = async function () {
const users = await getUsers();
const promises = [];
users.forEach(snapshot => {
promises.push(snapshot.ref.collection('monthlies').get());
});
const monthlies = await Promise.all(promises);
monthlies.forEach(snapshotArray => {
console.log(snapshotArray.docs.map(doc => doc.data()));
});
}
OR you could use the technique described in this article on how to use async/await inside a forEach()
.
Upvotes: 2
Reputation: 317868
In your code, element
is a QueryDocumentSnapshot type object. It doesn't have a method called collection()
, so I would expect your code will crash with an error in the log.
If you want to reference a subcollection organized under a document represented by QueryDocumentSnapshot, you should build upon its ref property:
users.forEach(snapshot => {
var monthlies = snapshot.ref.collection('monthlies').get()
console.log(monthlies.docs.map(doc => doc.data()))
})
Alternatively, if you just want to query all documents in all subcollections called "monthly", you can simplify that with a single collection group query.
Upvotes: 2