0

I want to check if a field exists in a document in firebase firestore or not.

4 Answers4

1

To check if a field exists in a document, simply use this code:

enter image description here

 Future updateUserFields() async {
    var userDoc = await FirebaseFirestore.instance.collection("uniaps_users").doc(uid).get();
    if (userDoc.exists) {
      Map<String, dynamic>? map = userDoc.data() as Map<String, dynamic>?;
      if (map!.containsKey('rooms')) {
        print("contains it");
      } else {
        print("does not contain it");
      }
    }
  }

The output will be: does not contain it

because in the document: FN1YRrruF2QQuYN0YV4492CpCge2 doesn't contain the rooms field.

The trick is to cast the userDoc.data() to be a map, so that you can be able to use the method containsKey('put the field here')

0
FirebaseFirestore.instance.collection('Products').doc(barcode).get().then((value) {

      if (value.data() !=null) {

        if (value.data().length>0) {

          /// Here I am checking if the field Trigram exist  <==///

          if (value.data()['Trigram']!=null) {

             searchTrigram=value.data()['Trigram'];

          } else {

             searchTrigram='';

          }

        }

      }

    });
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
0

Try this follow demo:

await fireStore
        .collection(AppConfig.instance.cUser)
        .doc(event.userId)
        .get()
        .then(
      (DocumentSnapshot documentSnapshot) {
        if (documentSnapshot.exists) {
          var data = documentSnapshot.data();
          var res = data as Map<String, dynamic>;
          
        } else {
          //do something
        }
      },
    );

And if you use in StreamBuilder:

StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance
                  .collection(AppConfig.instance.cUser)
                  .doc(AppConfig.instance.cListChat)
                  .collection(widget.userId)
                  .orderBy('create_at', descending: true)
                  .snapshots(),
              builder: (BuildContext context,
                  AsyncSnapshot<QuerySnapshot> chatSnapshot) {
                if (chatSnapshot.connectionState == ConnectionState.waiting) {
                  return Center(
                    child: Container(),
                  );
                }
                return ListView(
                  reverse: true,
                  controller: _controller,
                  physics: const BouncingScrollPhysics(),
                  children:
                      chatSnapshot.data!.docs.map((DocumentSnapshot document) {
                    if(document.exists){
                      Map<String, dynamic> data =
                      document.data()! as Map<String, dynamic>;
                      var _chat = ChatData.fromJson(data);
                      return Container();
                    } else {
                      return Container();
                    }
                  }).toList(),
                );
              },
            ),
Xuuan Thuc
  • 2,340
  • 1
  • 5
  • 22
0

I had a case with user and user's info:

First, I got user's data from Firebase:

Future<DocumentSnapshot> _getUserData() async {
    final user = FirebaseAuth.instance.currentUser;
    QuerySnapshot querySnapshot = await _db
        .collection('users')
        .where('email', isEqualTo: user!.email.toString())
        .get();
    DocumentSnapshot userDoc = querySnapshot.docs.first;
    return userDoc;
}

Saved it in variable

AsyncSnapshot<DocumentSnapshot<Object?>> user = snapshot;

And latere when I wanted to check if description field in user object exists:

String description = user.data!.data().containsKey('description')
    ? user.data!.get('description')
    : "-";
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Skar
  • 333
  • 2
  • 11