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

前端 未结 6 1635
野性不改
野性不改 2020-12-28 15:15

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?

6条回答
  •  攒了一身酷
    2020-12-28 15:53

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

提交回复
热议问题