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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46880323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:39:10  来源:igfitidea点击:

How to check if a cloud firestore document exists when using realtime updates

javascriptgoogle-cloud-firestore

提问by Stewart Ellis

This works:

这有效:

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

... but it seems verbose. I tried doc.exists, but that didn't work. I just want to check if the document exists, before subscribing to realtime updates on it. That initial get seems like a wasted call to the db.

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

Is there a better way?

有没有更好的办法?

回答by Excellence Ilesanmi

Your initial approach is right, but it may be less verbose to assign the document reference to a variable like so:

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

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
    }
});

Reference: Get a document

参考:获取文档