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

JavascriptGoogle Cloud-Firestore

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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][1] [1]: https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document

Solution 2 - Javascript

Please check following code. It may help you.

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

Solution 3 - Javascript

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 

Solution 4 - Javascript

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/

Solution 5 - Javascript

Please note that in Firebase v9 (Modular SDK) exists is a method, not a property (which would give you falsy results all the time), as per the docs.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStewart EllisView Question on Stackoverflow
Solution 1 - JavascriptExcellence IlesanmiView Answer on Stackoverflow
Solution 2 - JavascriptDwipal ParmarView Answer on Stackoverflow
Solution 3 - JavascriptdealdreyView Answer on Stackoverflow
Solution 4 - JavascriptNowdeenView Answer on Stackoverflow
Solution 5 - JavascriptEduardView Answer on Stackoverflow