首页 > 解决方案 > 如何添加文档并将其 ID 立即存储在 Firebase 的其他地方?使用本机反应

问题描述

我正在尝试在我的相册集合中创建一个文档,然后获取创建的新文档的 ID 并将其存储在我的 Firestore 的其他位置。这是我的代码和错误消息。

const createAlbum = () => {
firebase
  .firestore()
  .collection("albums")
  .add(albumName)
  .then((snapshot) => {
    let newAlbum = snapshot.docs.map((doc) => {
      const id = doc.id;
      return id;
    });
    for (let i = 0; i < usersSelected.length; i++) {
      firebase
        .firestore()
        .collection("following")
        .doc(usersSelected[i].id)
        .collection("userFollowing")
        .doc(newAlbum.id)
        .set({});
    }
  });

};

[未处理的承诺拒绝:TypeError:未定义不是对象(评估'snapshot.docs.map')]在[本机代码]:在[本机代码]的flushedQueue中为null:在callFunctionReturnFlushedQueue中为null

标签: javascriptreactjsfirebasereact-nativegoogle-cloud-firestore

解决方案


尝试这样的事情:

const createAlbum = () => {
  firebase
    .firestore()
    .collection("albums")
    .add(albumName)
    .then((doc) => {
      const id = doc.id;
      for (let i = 0; i < usersSelected.length; i++) {
        firebase
          .firestore()
          .collection("following")
          .doc(usersSelected[i].id)
          .collection("userFollowing")
          .doc(id)
          .set({ });
      }
    });
}

推荐阅读