Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 974
Dyan Avatar asked Oct 25 '18 02:10

Dyan


2 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);
    });
like image 140
Alex Mamo Avatar answered Oct 28 '22 23:10

Alex Mamo


I think you refer to making a query. Still there is no way to check if some field is present or not in the Firestore. But you can add another field with value true/false

val query = refUsersCollection
        .whereEqualTo("hasLocation", true)
query.get().addOnSuccessListener { 
      // use the result
  }

check out this links for more

https://firebase.google.com/docs/firestore/query-data/queries How do I get documents where a specific field exists/does not exists in Firebase Cloud Firestore?

like image 43
Dan Alboteanu Avatar answered Oct 29 '22 01:10

Dan Alboteanu