Search code examples
fluttergoogle-cloud-firestorefirebase-securityflutter-getx

firestore: how to check if a document exist


I have a collection admins in my firestore, where i add document IDs of users with admin roles.

In other to grant users admin role, i need to check if their users ID (documentID) is found under admin collection.

here is my code:

isAdmin() async {
await getUser.then((user) async {
  final adminRef = await _db.collection("admins").doc(user?.uid).get();
  if (adminRef.exists) {
    admin.value = true;
  } else {
    admin.value = false;
  }
  update();
}); }

It keeps returning false where as the document of the current user exist under admins.

when i replace the collection in the query by users, it works fine.

i don't know where i'm going wrong. any clue please?

here is admins collection image image of admins collection

here is users collection image image of users collection


Solution

  • This will work. data() method will return null if no document present and return {} when the blank / empty document present.

    isAdmin() async {
    await getUser.then((user) async {
      final adminRef = await _db.collection("admins").doc(user).get();
      if (adminRef.data() == {}) {
        admin.value = true;
      } else {
        admin.value = false;
      }
      update();
    }); }
    

    I didn't get why you are creating empty documents inside the collection. Instead you can store the userId of admin in the each document and assign userId as a documentId. and you can check it by using where queries.