繁体   English   中英

在 Firestore 中通过 docId 批量设置文档字段时遇到问题

[英]Trouble batch setting a document field by docId in Firestore

我一直在使用 firebase (firestore) 一段时间,但我有点卡住了,想知道是否有人能想到一个解决方案。

在 Firestore DB 上,我有一个用户集合,每个用户都有一个 email 地址和其他几个字段。 在这种情况下,我正在检查用户 email 是否存在,如果存在,我想使用 listUid 为该特定用户创建一个列表字段。 我通过 email 引用用户,获取这些用户的 docId,然后尝试为每个用户设置一个列表字段。

我没有从firestore收到任何错误,它只是由于某种原因没有在数据库中更新,我不知道我哪里出错了。 提前致谢

export const addListUidToExistingUserList = (
  { firestore },
  emailArray,
  listUid
) => {
  return async () => {
    let docIds = [];

    emailArray.forEach((emailAddress) => {
      //find users by email (works)
      const query = db
        .collection("users")
        .where("email", "==", emailAddress);

      //get docId's for user with matching email (works)
      query.get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          docIds.push(doc.id);
        });
      });

      //add a new list with corresponding listUid (does not work)
      docIds.forEach((id) => {
        let userRef = db.collection("users").doc(id);
        batch.set(userRef, { lists: [{ listUid }] });
      });
    });
    return await batch.commit();
  };
};

您遇到此问题是因为您的docIds数组在您调用docIds.forEach时始终为空。

那是因为query.get().then异步运行,所以docIds.forEach不会等待它完成。

您可以:

  • await query.get().then 或者
  • 在 query.get 的then回调中添加docIds.forEach query.get

以下是您可能的修复:

  1. await query.get().then
//get docId's for user with matching email (works)
await query.get().then((querySnapshot) => {
  querySnapshot.forEach((doc) => {
    docIds.push(doc.id);
  });
});

或者:

  1. docIds.forEach里面then
//get docId's for user with matching email (works)
query.get().then((querySnapshot) => {
  querySnapshot.forEach((doc) => {
    docIds.push(doc.id);
  });

  docIds.forEach((id) => {
    let userRef = db.collection("users").doc(id);
    batch.set(userRef, { lists: [{ listUid }] });
  });
});

注意:当然,您也可以将batch.set直接添加到querySnapshot.docs.forEach的第一次迭代中,以防止不必要的迭代。

暂无
暂无

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

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