Home > Net >  How to check if given document exists in firebase firestore
How to check if given document exists in firebase firestore

Time:05-30

I am trying to add user data in firestore database with document name 'uid' when someone signs in with google. Here, data should only be added to firestore if a document with the same uid does not exist.

How do I check?

Function for google signin

Future googleLogIn() async {
  try {
    final googleUser = await googleSignIn.signIn();
    if (googleUser == null) return;
    _user = googleUser;
    final googleAuth = await googleUser.authentication;
    final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);

    await FirebaseAuth.instance.signInWithCredential(credential);
    notifyListeners();
  } on Exception catch (e) {
    print(e.toString());
  }
}

Function for inserting user data in database

Future<void> userSetup(
  String displayName, String email, String photoUrl) async {
  FirebaseAuth auth = FirebaseAuth.instance;
  String? uid = auth.currentUser?.uid.toString();
  CollectionReference users = FirebaseFirestore.instance.collection('UserData');
  users.add({
    'uid': uid,
    'displayName': displayName,
    'email': email,
    'photoUrl': photoUrl
  });
  return;
}

CodePudding user response:

Consider saving the user document by using the user id as key. You can check if the document already exists, by calling:

final doc = await FirebaseFirestore.instance.collection('UserData').doc(userID).get();
final bool doesDocExist = doc.exists;

However this costs you an extra read whenever your user logs in. You could use custom claims instead, but this requires you to use the firebase admin sdk. Documentation

CodePudding user response:

As Janik answered using the UID as the key is the idiomatic approach for this. Since a document ID is by definition unique in its collection, using the UID as the document ID is guaranteed to prevent duplicates without you having to do anything for it.

With that, I'd recommend against doing a read-and-then-write, as there's no harm in simply always writing/updating the user data when they sign in.

If you must do a read-and-then-write, be sure to use a transaction to prevent accidental overwrites.

  • Related