问题描述
在扑朔迷离中,我正在使用Firestore存储我登录的用户.
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.
要检查是否存在与该用户相对应的文档,我想通过其"id"(即文档中的字段)而不是文档标签来进行检查,因为我是从firebase api获取"id"的.
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']
});
我尝试使用以下方法检查用户是否存在,但始终返回false
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;
推荐答案
下面是一个示例,该示例将检查用户是否存在以及是否存在,它将通过简单地使用合并来覆盖以前的数据.
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);
}
我希望它将对您有帮助
这篇关于flutter-如果不存在则添加到Firestore集合中,否则更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!