Kuldip Bhutoria
Kuldip Bhutoria

Reputation: 86

How can you check if a field exists in a document/documentSnapshot or not?

There is a public method called contains(string fieldName) in the documentSnapshot documentations. https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/DocumentSnapshot#public-method-summary

But when I use this method in my code, I always get an error code like TypeError: documentSnapshot.contains is not a function

Did I get it wrong? Is there a workaround for this?

Here is an example of what I am trying to do.

let citiesRef = db.collection('cities');
let allCities = citiesRef.get()
  .then(snapshot => {
    snapshot.forEach(doc => {
      if(doc.contains('states'){
      console.log(doc.id, '=>', doc.data());
     };
    });
  })
  .catch(err => {
    console.log('Error getting documents', err);
  });

Upvotes: 2

Views: 2160

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

You are using Javascript, and the reference that you linked is for Android. In Javascript, you can use the method get():

   snapshot.forEach(doc => {
      if(doc.get('states') != null){
      console.log(doc.id, '=>', doc.data());
     };
    });

Upvotes: 2

Related Questions