How to check if a document contains a property in Cloud Firestore?

Viewed 11341

I want to know if there is a way to check if a property is present in a Cloud Firestore document. Something like document.contains("property_name") or if there is a document property exist.

3 Answers

To solve this, you can simply check the DocumentSnapshot object for nullity like this:

var yourRef = db.collection('yourCollection').doc('yourDocument');
var getDoc = yourRef.get()
    .then(doc => {
      if (!doc.exists) {
        console.log('No such document!');
      } else {
        if(doc.get('yourPropertyName') != null) {
          console.log('Document data:', doc.data());
        } else {
          console.log('yourPropertyName does not exist!');
        }
      }
    })
    .catch(err => {
      console.log('Error getting document', err);
    });

You could use the in operator like in the snippet bellow

  const ref = admin.firestore().collection('yourCollectionName').doc('yourDocName')
  try {
    const res = await ref.get()
    const data = res.data()    
    if (!res.exists) {
      if (!("yourPropertyName" in data)) {
         // Do your thing
      }
    } else {
         // Do your other thing
    }
  } catch (err) {
    res.send({err: 'Something went terribly wrong'})
  }
Related