【问题标题】:How to get document after set method in firestore while updating更新时如何在firestore中设置方法后获取文档
【发布时间】:2020-08-09 04:00:12
【问题描述】:

我正在更新我的文档。我使用 set 方法是因为我想覆盖我的字段。因此,当我做我的设置时,它可以完美地工作,修改 firestore 数据库中的对象。但之后我无法退回文件。我得到的错误:

Cannot read property 'exists' of undefined
    at Firebase.js:127

这是我的代码:

const updateItemFromCollection = async (collectionName, uid, data) => {
  return database
    .collection(collectionName)
    .doc(uid)
    .set(data, { merge: true })
    .then(doc => {
      if (!doc.exists) {
        console.log("No such document!"); //Error
      } else {
        return doc.data();
      }
    })
    .catch(error => {
      console.log(error);
    });
};

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    这是因为set() 方法返回的是Promise<void> 而不是Promise<DocumentSnapshot<T>>

    您需要再次阅读文档,如下:

    const updateItemFromCollection = async (collectionName, uid, data) => {
    
      const docRef = database.collection(collectionName).doc(uid);
    
      return docRef.set(data, { merge: true })
        .then(() => {
            return docRef.get();
        .then(doc => {
          if (!doc.exists) {
            console.log("No such document!"); //Error
          } else {
            return doc.data();
          }
        })
        .catch(error => {
          console.log(error);
        });
    };
    

    这是 Firestore 的工作方式,AFAIK 是基于您已经知道文档字段的值这一事实,因为您将相应的对象传递给 set()。然而,有人可能会说,对于后端根据哨点值计算的值,这不是真的,请参阅FieldValue

    【讨论】:

    • 谢谢,这正是我所做的,只是使用了已经传递的数据。
    猜你喜欢
    • 2021-06-11
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 2016-06-08
    • 2018-09-03
    相关资源
    最近更新 更多