Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 536
Stewart Ellis Avatar asked Oct 22 '17 23:10

Stewart Ellis


People also ask

Can I use realtime database and firestore at the same time?

You can use both Firebase Realtime Database and Cloud Firestore in your app, and leverage each database solution's benefits to fit your needs. For example, you might want to leverage Realtime Database's support for presence, as outlined in Build Presence in Cloud Firestore.

What is the difference between cloud firestore and realtime database?

Cloud Firestore is Firebase's newest database for mobile app development. It builds on the successes of the Realtime Database with a new, more intuitive data model. Cloud Firestore also features richer, faster queries and scales further than the Realtime Database. Realtime Database is Firebase's original database.


2 Answers

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

like image 89
Excellence Ilesanmi Avatar answered Sep 19 '22 12:09

Excellence Ilesanmi


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());    } 
like image 29
Dwipal Parmar Avatar answered Sep 21 '22 12:09

Dwipal Parmar