在Firebase Firestore中实施唯一的userId [英] Enforcing unique userIds in Firebase Firestore
问题描述
我正在使用Firebase的新Firestore数据库,并想知道是否存在一种更有效的方法来实施唯一的用户名(或唯一的子节点).
I'm playing around with the new Firestore database from Firebase and was wondering if there was a more efficient way to enforce unique usernames (or unique child nodes).
我使用电子邮件/密码身份验证,但允许用户创建唯一的句柄,例如Twitter.
I use email/password auth but allow users to create a unique handle, like Twitter.
借助实时数据库,我能够通过事务和多节点结构实现这一目标.
With the Realtime database I was able to achieve this with transactions and a multiple node structure.
-users
-uid1234:
-username: ryan
-usernames:
-ryan: uid1234
我当时在想,如果没有多余的 usernames
节点(使用文档作为Firestore中的用户名),则有可能做到这一点.
I was thinking it may be possible to do this without the extra usernames
node using documents as the username in Firestore.
推荐答案
您可能可以通过2种方法来做到这一点.创建用户之前,请先与另一个呼叫联系,以确认该用户是否存在于具有用户名的集合中.
You could do it probably do it in 2 ways. Check with a separate call before create user, if the user exist in an collection with usernames.
您还可以创建类似以下规则:
Also you could create a rule like:
match /users/{document=**} {
allow create: if !exists(/databases/$(database)/documents/usernames/$(request.resource.data.username));
}
在这种情况下,如果用户名在创建时已经存在并且您可以捕获代码,则会返回一个错误.
In that case you get a error back if the username already exist on creating and that you can catch in the code.
这篇关于在Firebase Firestore中实施唯一的userId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!