How to check if a document contains a property in Cloud Firestore?
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'})
}
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?
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);
});