问题
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).
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
I was thinking it may be possible to do this without the extra usernames node using documents as the username in Firestore.
回答1:
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.
来源:https://stackoverflow.com/questions/47298750/enforcing-unique-userids-in-firebase-firestore