简体   繁体   English

循环查询 FireStore 文档

[英]Querying for FireStore docs in a loop

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).我从单个集合 (A) 查询并获取文档数组,然后我想通过数组中的每个文档进行 go,并根据第一个集合中每个文档中的值从另一个集合 (B) 中查询(一种)。

Here is my code, I have tried both async/await (shown in this example) as well .then with Promise.all()这是我的代码,我也尝试了async/await (在此示例中显示)。然后使用.then 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" });
};

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. forEach关闭器不期望async function,因此该循环中的await insode 不会使forEach周围的代码等待任何东西。

To make the entire loop wait, use for of :要让整个循环等待,请使用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另请参阅: 将 async/await 与 forEach 循环结合使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM