My Firestore Database :
i want to check if there is a field named "EmailOf@Follower.com" exist in Doc "D9GeGdTxarFruuuQklEO" only ,, not checking in all docs ,, anyway to do that in firestore Flutter ?
My Firestore Database :
i want to check if there is a field named "EmailOf@Follower.com" exist in Doc "D9GeGdTxarFruuuQklEO" only ,, not checking in all docs ,, anyway to do that in firestore Flutter ?
From cloud_firestore: ^0.14.0 to up you can check if a particular field exist in a documentSnapshot by doing this:
CollectionReference users = FirebaseFirestore.instance.collection('users');
var doc = await users.doc(id).get();
if(doc.exists){
Map<String, dynamic> map = doc.data();
if(map.containsKey('field')){// Replace field by the field you want to check.
var valueOfField = map['field'];
}
}
or you can also do this:
await _users.doc(id).get().then((doc){
if(doc.exists){
doc.data().forEach((key, value) {
if(key == 'field'){
var valueOfField = value;
}
});
}
});
If you want to know anything at all about the contents of a document, you have to read it and examine its fields. There is no special operation for checking fields without reading the document.
issue of using .where(yourField, '==', null) is you don't know if yourField actually exists and has null value or doesn't exist
if yourField is the field that you want to know if it exists,
const orderRef = db.collection("YOUR_COLLECTION")
const docSanpshots = await orderRef.get()
docSanpshots.docs.forEach((doc) => {
if (doc.get('yourField') === undefined) {
// DO SOMETHING HERE when yourField doesn't exist
}
})
notice that yourField is wrapped with quotes
I got another solution not mentioned above for who not worked with him the others solution.
the idea is to convert the Object data to Map type.
so first of all you need to import this
import 'dart:convert';
in your dart file then we will encode the object data to get it as Map type
jsonEncode(documentSnapshot.data()).contains('your_field')
You can use the key name to check if it exists against an undefined value
const orderSnap = await db.collection("YOUR_COLLECTION").where("user_id","==","01").get();
if (orderSnap.data().yourField == undefined) {
// DO SOMETHING HERE when yourField doesn't exist
}