【问题标题】:How to check if a cloud firestore document exists when using realtime updates使用实时更新时如何检查 Cloud Firestore 文档是否存在
【发布时间】:2018-04-03 11:14:15
【问题描述】:

这行得通:

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

有没有更好的办法?

【问题讨论】:

  • 您是要完成插入/更新还是?
  • 现在是db.collection('users').doc('id').ref.get()

标签: javascript google-cloud-firestore


【解决方案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
    }
});

参考:Get a document

【讨论】:

  • 你拯救了我的一天。谢谢!
【解决方案2】:

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

 const userDocRef = FirebaseFirestore.instance.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());
   }

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      $firestore = new FirestoreClient();
      $document = $firestore->document('users/john');
      $snapshot = $document->snapshot();
      
      if ($snapshot->exists()) {
         echo "John is there!";
      }
      

      享受吧! o/

      【讨论】:

        【解决方案5】:

        请注意,在 Firebase v9(模块化 SDK)中,exists 是一种方法,而不是属性(它会一直为您提供 falsy 结果),如 docs 所述。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-03-23
          • 2021-07-22
          • 1970-01-01
          • 2020-04-24
          • 2018-11-18
          • 2021-11-25
          • 1970-01-01
          • 2021-12-29
          相关资源
          最近更新 更多