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

Stewart Ellis picture Stewart Ellis · Oct 23, 2017 · Viewed 66.3k times · Source

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?

Answer

Excellence Ilesanmi picture Excellence Ilesanmi · Oct 27, 2017

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