简体   繁体   中英

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

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.

Is there a better way?

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

In case you are using PHP-Firestore integration, like me, write something like this:

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

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

Enjoy! o/

Please check following code. It may help you.

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

I know its late, but it's actually snapshot.empty not snapshot.exists . snapshot.empty checks if a doc exists and returns accordingly. happy coding 😊

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

If you are using Angular you can use the AngularFire package to check it with an observable.

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) {
      // ...
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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