I have a collection of items, with each item linked to multiple transaction records.
- items
- itemA
- transactionA
- transactionB
- itemB
- transactionC
- transactionD
In my express application, I need to create an endpoint that retrieves all items along with their associated transactions as shown above.
The challenge lies in synchronizing Firebase with async-await. I attempted to utilize Promise.all()
but encountered difficulties with nested operations:
let items = await db
.collection(collections.items)
.where("active", "==", true)
.get()
.then(async (snapshot) => {
let itemList = [];
snapshot.forEach(async (doc) => {
let transactions = await doc.ref
.collection("transactions")
.get()
.then(async (transactionSnapshot) => {
let promises = [];
transactionSnapshot.forEach(async (transactionDoc) => {
promises.push(transactionDoc.data());
});
return Promise.all(promises);
});
functions.logger.log("transactions", transactions);
itemList.push({ data: doc, transactions });
});
return Promise.all(itemList);
});
functions.logger.log("items", items);
res.status(BASIC_HTTP_STATUS_CODES.success).json({ items });
Upon reviewing the logs, I noticed that some transactions are logged after the items, and the returned object is empty.
The code works fine when querying only the items without their transactions.
How can I ensure that the program waits for all item documents to finish attaching their respective transaction details before proceeding?