0

I am building a money tracking application and trying to fetch a subcollection called "contributions" which belongs to a "saving" document. I am confident my reference is correct as I have build the same reference elsewhere in my application and it works perfectly however upon using getDocs() with this reference it results in the error: Possible Unhandled Promise Rejection (id: 0): TypeError: cannot add a new property this error makes little sense to me as I am not attempting to modify or set any data, only fetch from firestore.

I have validated the collection reference I am providing is correct. Here is my code:

let savings = [];
const savingsRef = collection(userRef, "savings");
const savingsSnapshot = await getDocs(savingsRef);
savingsSnapshot.forEach(async(doc) => {
    let contributions = [];
    let currentSum = 0;
    const contributionsRef = collection(doc.ref, "contributions"); // this is a valid collection refrence
    const contributionsSnapshot = await getDocs(contributionsRef); // this line causes the error
    contributionsSnapshot.forEach((doc) => {
        console.log(doc.data());
        contributions.push({ ref: doc.ref, ...doc.data() });
        currentSum += Number(doc.data().amount);
    });
    savings.push({
        ref: doc.ref,
        ...doc.data(),
    });
});
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 1
    Your use of `await` inside a `forEach` loop isn't going to work the way you expect. It's not blocking the execution of the loop. See: https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Doug Stevenson Aug 28 '23 at 22:02
  • Thanks a bunch @DougStevenson, I implemented my loop properly and the issue seems to be resolved. – Nicolas Woodcock Aug 28 '23 at 22:32

0 Answers0