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

Solution 1:

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

Solution 2:

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