繁体   English   中英

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

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

这有效:

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 似乎是对数据库的浪费调用。

有没有更好的办法?

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

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

参考: 获取文档

如果您像我一样使用 PHP-Firestore 集成,请编写如下内容:

$firestore = new FirestoreClient();
$document = $firestore->document('users/john');
$snapshot = $document->snapshot();

if ($snapshot->exists()) {
   echo "John is there!";
}

享受! o/

请检查以下代码。 它可能会帮助你。

 const userDocRef = await firestore().collection('collection_name').doc('doc_id');
   const doc = await userDocRef.get();
   if (!doc.exists) {
     console.log('No such document exista!');
   } else {
     console.log('Document data:', doc.data());
   }

我知道它迟到了,但它实际上是 snapshot.empty 而不是 snapshot.exists 。 snapshot.empty 检查文档是否存在并相应返回。 快乐编码😊

请注意,在火力地堡V9(模块化SDK) exists是一种方法,而不是一个属性(它会给你falsy结果所有的时间),按照该文档

如果您使用的是Angular,则可以使用AngularFire包以可观察的方式对其进行检查。

import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';

constructor(private db: AngularFirestore) {
  const ref: AngularFirestoreDocument<any> = db.doc(`users/id`);
  ref.get().subscribe(snap => {
    if (snap.exists) {
      // ...
    }
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM