What's the best way to check if a Firestore record exists if its path is known?

David Haddad picture David Haddad · Nov 15, 2017 · Viewed 36.2k times · Source

Given a given Firestore path what's the easiest and most elegant way to check if that record exists or not short of creating a document observable and subscribing to it?

Answer

DoesData picture DoesData · Nov 15, 2017

Taking a look at this question it looks like .exists can still be used just like with the standard Firebase database. Additionally, you can find some more people talking about this issue on github here

The documentation states

NEW EXAMPLE

const cityRef = db.collection('cities').doc('SF');
const doc = await cityRef.get();
    
if (!doc.exists) {
    console.log('No such document!');
} else {
    console.log('Document data:', doc.data());
}

Note: If there is no document at the location referenced by docRef, the resulting document will be empty and calling exists on it will return false.

OLD EXAMPLE

var cityRef = db.collection('cities').doc('SF');

var getDoc = cityRef.get()
    .then(doc => {
        if (!doc.exists) {
            console.log('No such document!');
        } else {
            console.log('Document data:', doc.data());
        }
    })
    .catch(err => {
        console.log('Error getting document', err);
    });