flutter - add to firestore collection if not exists otherwise update

偶尔善良 提交于 2020-08-11 03:33:32

问题


In flutter, I am using firestore to store my users that log in.

I want if a user login the first time to add his information to a collection.

If he logout, then logs in, I want to update his document in the collection.

To check if there is a document corresponding to the user, I want to check by his 'id' which is a field in the document, and not by the document tag, since I get the 'id' from firebase api.

Here is the add which is working correctly

_firestore.collection('profiles').add({
        'firebase_id': profile['user_id'],
        'first_name': profile['first_name'],
        'last_name': profile['last_name'],
        'login_date': profile['login_date']
});

I tried to check if the user exists using the following but it returns always false

bool isEmpty = await _firestore
            .collection('profiles')
            .where('firebase_id', isEqualTo: profile['user_id'])
            .snapshots()
            .first
            .isEmpty;

回答1:


Here an example that will check if the users exist or not and if it exists it will overwrite the previous data by simply using merge.

DocumentReference ref = _db.collection('users').document(user.uid);

return ref.setData({
  'uid': user.uid,
  'email': user.email,
  'photoURL': user.photoUrl,
  'displayName': user.displayName,
  'lastSeen': DateTime.now()
}, merge: true);

}

I hope it will help you




回答2:


when you save users in the firestore make the documentID equal to userID.

Firestore.instance.collection('profiles').document( profile['user_id']).setData({
        'firebase_id': profile['user_id'],
        'first_name': profile['first_name'],
        'last_name': profile['last_name'],
        'login_date': profile['login_date']
});

then check if exists.

 bool userExists=(await Firestore.instance.collection('profiles').document('userid').get()).exists;


来源:https://stackoverflow.com/questions/58888939/flutter-add-to-firestore-collection-if-not-exists-otherwise-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!