Home > Enterprise >  Querying for FireStore docs in a loop
Querying for FireStore docs in a loop

Time:11-20

I've seen some other people post this question and I have tried the solutions they said work, however nothing has worked for me thus far.

I am querying from a single collection (A) and getting an array of documents, then I want to go through each of the docs in the array and query from another collection (B) based on a value in each doc from the first collection (A).

Here is my code, I have tried both async/await (shown in this example) as well .then with Promise.all()

export const getUserEvents = async (req: Request, res: Response) => {
  console.log("getUserEvents:req.params.userId: ", req.params.userId);

  try {
    let events: Event[] = [];
    const snapshot = await db.collection("eventPeople").where("userId", "==", req.params.userId).get();
    snapshot.forEach(async (doc) => {
      const eventRef = await db.collection("events").where("eventId", "==", doc.data().eventId).get();

      eventRef.forEach((eventDoc) => {
        console.log("event: ", eventDoc.data())
      });
    });

    console.log("events: ", events)

    return res.json({ events: events });
  } catch (err) {
    functions.logger.error("unable to query eventPeople using userId", { userId: req.params.userId, error: err });
  }

  return res.json({ events: "events" });
};

CodePudding user response:

forEach closers don't expect an async function, so the await insode that loop doesn't make the code around the forEach wait for anything.

To make the entire loop wait, use for of:

for (const doc of snapshot.docs) {
  const eventRef = await db.collection("events").where("eventId", "==", doc.data().eventId).get();

  eventRef.forEach((eventDoc) => {
    console.log("event: ", eventDoc.data())
  });
}

Also see: Using async/await with a forEach loop

  • Related