Search code examples
firebaseangularfire2google-cloud-firestore

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


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?


Solution

  • 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

    var docRef = db.collection("cities").doc("SF");
    
    docRef.get().then((doc) => {
        if (doc.exists) {
            console.log("Document data:", doc.data());
        } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
        }
    }).catch((error) => {
        console.log("Error getting document:", error);
    });
    

    OLD 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 2

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