使用实时更新时如何检查云 firestore 文档是否存在

新手上路,请多包涵

这有效:

 db.collection('users').doc('id').get()
  .then((docSnapshot) => {
    if (docSnapshot.exists) {
      db.collection('users').doc('id')
        .onSnapshot((doc) => {
          // do stuff with the data
        });
    }
  });

…但它似乎很冗长。我尝试 doc.exists ,但是没有用。在订阅实时更新之前,我只想检查文档是否存在。最初的 get 似乎是对数据库的浪费调用。

有没有更好的办法?

原文由 Stewart Ellis 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 449
1 个回答

您最初的方法是正确的,但将文档引用分配给变量可能不那么冗长,如下所示:

 const usersRef = db.collection('users').doc('id')

usersRef.get()
  .then((docSnapshot) => {
    if (docSnapshot.exists) {
      usersRef.onSnapshot((doc) => {
        // do stuff with the data
      });
    } else {
      usersRef.set({...}) // create the document
    }
});

参考: 获取文档

原文由 Excellence Ilesanmi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题