I am trying to get all the documents in a collection and .forEach
document do a query of a sub collection and get the latest (by date) document out of it, but for some reason the query size always is 0
Here is the code:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
/// Updates the last payment done in the neighbors documents
export const updateLastPaymentHTTP = functions.https.onRequest(
async (request, response) => {
try {
const neighbors = await admin.firestore()
.collection("neighbors").get();
const promises = [];
neighbors.forEach(async (neighbor) => {
const topPaymentRef = admin.firestore()
.collection(`neighbors/${neighbor.ref}/payments`)
.orderBy("date", "desc")
.limit(1)
.get();
const querySize = await topPaymentRef.then((query) => query.size);
console.log(`Query Size: ${querySize}`);
if (querySize === 1) {
const lastPayment = (await topPaymentRef).docs[0].data();
promises.push(neighbor.ref.update({ last_payment: lastPayment }));
} else {
promises.push(neighbor.ref.update({ last_payment: "" }));
}
});
await Promise.all(promises);
response.send("Update Last Payments Completed");
} catch (error) {
console.log(`Error Updating Last Payment ${error}`);
}
}
);
I do the query check because in some neighbor documents there is not a sub collection called payments but in most of them there is:
and
But my querySize === 1
is always false and i update { last_payment: '' }
. I have also tried every option explained here, Is there something wrong with my collection query?