如何避免在firebase文档中输入重复的数据?
我的数据库非常简单。一个集合,里面有包含用户信息的文档,包括他们的用户名。
(我正在 flutter 和 firestore 中执行此操作)。
我想要的是防止两个用户拥有相同的用户名。
我这样做是为了插入数据。
FirebaseFirestore.instance.collection('users').add({
'username': 'username',
'desc': 'some bio',
'fieldone': 'aaa',
'fieldtwo': 'bbb',
// other user info
});
并查阅用户的数据(通过用户名)。
FirebaseFirestore.instance.collection('users').where('username', isEqualTo: 'username').get();
当我插入数据时,我可以做什么来验证所述用户名是否已经在数据库中? 因此,如果用户名已经存在,则返回错误并且不允许插入它。如果尚不存在,则可以将其插入。
什么查询可以帮助我解决这个问题? 我是 firebase 新手。 :(。 谢谢。
My database is quite simple. A collection and inside, there are documents with user information, including their username.
(I am doing this in flutter and firestore).
What I want is to prevent two users from having the same username.
I am doing this to insert the data.
FirebaseFirestore.instance.collection('users').add({
'username': 'username',
'desc': 'some bio',
'fieldone': 'aaa',
'fieldtwo': 'bbb',
// other user info
});
And to consult the data of a user (by their username).
FirebaseFirestore.instance.collection('users').where('username', isEqualTo: 'username').get();
At the moment I insert the data, what can I do to verify that said username is already in the database?
So if the username already exists, return an error and don't let insert it. And if it doesn't exist yet, it can be inserted.
What query can help me for this?
I am new to firebase. :(. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这无法通过单个查询来完成。您必须采取您在问题中概述的步骤。您必须首先查询具有该用户名的文档,然后仅在找不到时插入新文档。
但是,您应该意识到这里存在竞争条件。如果两个人同时尝试添加相同的用户名,则他们最终可能都会添加一个文档。
确保 Firestore 中唯一性的唯一方法是使用文档 ID。您可能需要考虑使用文档的 ID 来存储用户名(或它的某种版本,例如哈希值),以便永远不会发生竞争条件,并且您只有一个具有该用户名的文档。
另请参阅:
如您所见,您的问题已经得到彻底讨论在堆栈溢出上。
This can't be accomplished by a single query. You will have to take the steps you outlined already in your question. You will have to first query for documents with that username, then only insert a new one if there were none found.
However, you should be aware that there is a race condition here. If two people are trying at the same time to add the same username, it's possible that they both end up adding a document.
The only way to ensure uniqueness in Firestore is using the document ID. You might want to consider using the ID of the document to store the username (or some version of it, like a hash) so that a race condition can never occur, and that you only have one document with that username.
See also:
As you can see, your issue has already been thoroughly discussed on Stack Overflow.