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

Ste*_*lis 26 javascript google-cloud-firestore

这有效:

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

......但似乎很冗长.我试过doc.exists,但那没用.我只想在订阅文档上的实时更新之前检查文档是否存在.那个初始的get似乎是对db的一个腰部调用.

有没有更好的办法?

Exc*_*nmi 59

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

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
    }
});
Run Code Online (Sandbox Code Playgroud)

参考:获取文档

  • 你拯救了我的日子。谢谢! (2认同)

小智 19

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

 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());
   }
Run Code Online (Sandbox Code Playgroud)