使用实时更新时如何检查云 Firestore 文档是否存在 [英] How to check if a cloud firestore document exists when using realtime updates

查看:18
本文介绍了使用实时更新时如何检查云 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 似乎是对数据库的浪费调用.

... 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.

有更好的方法吗?

推荐答案

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

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

参考:获取文档

这篇关于使用实时更新时如何检查云 Firestore 文档是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆