Cloud Firestore doesn't yet support batch read of documents in a collection and so the next best thing is to use firestore.getAll()
to retrieve documents given an array of ObjectId's as given in this link.
A similar question has already been posted and the above function was the answer to the question. But when I run the same snippet it somehow isn't working. Can someone please tell me why?
db.collection("users")
.doc(uid)
.get()
.then(data => {
// return array of accountId's associated with user
return data.data().accounts;
})
.then(arr => {
console.log(arr);
if (!arr) {
res.json({ message: "no associated accounts" }); // check if array is empty
}
let userAccounts = [], docRefs = [];
arr.forEach(id => docRefs.push(db.doc(`accounts/${id})`))); // dynamically creating DocumentReferences for each _id
console.log(docRefs); // valid output -> an array of 2 DocumentReference() objects
db.getAll(...docRefs).then(docs => { // I
docs.forEach(doc => {
if (doc.exists) {
console.log(doc.data()); // II
userAccounts.push(doc.data());
}
});
});
console.log(userAccounts); // III
res.json(userAccounts);
})
.catch(err => {
res.status(500).json({
status: err.code,
message: err.message
});
});
- I. Since it's a dynamically generated array, I've used the spread operator.
- II. This line is never executed as there is no output for this
console.log()
statement, not even anundefined
. - III. Therefore the
userAccounts
is still[]
after this, since II is never executed and neither is thepush()
after that and so, this is the response I get. No errors.
P.S. The arr
is fine. I've cross-checked with the db. The db
variable is a firestore()
object.