Proper way to maintain unique usernames and extra profile data in Firebase

扶醉桌前 提交于 2019-12-04 05:29:15

问题


I am trying to create a separate datastore for unique usernames and extra profile data such as avatar etc. I have the following schema:

mydatabase : {
   users: [{
     <actual user's id>: {
        username: "helloworld"
     },
     <actual user's id>: {
        username: "2test"
     }]
}

Is my approach correct on this? I didn't see a way in firebase to store usernames or extra user data in the Authentication records of firebase. Also I noticed most examples I find online generate a push key for each row of data, but here I am using the actual user's id instead of a push key. I want to eventually query this when a user tries to create a username to see if it's been taken already.


回答1:


I would use the same approach you're using. I agree that it makes sense to use the userId as the key instead of a pushId since, as you point out, you'll want to query the data later on.

The only potential challenge of using this structure is if you want users to pick a username at the time the user is created, they will not have read access to the database so they won't be able to check if the username is unique. As long as you're ok with creating a user first and then having them choose a username once authenticated, this won't be a problem. If you'd prefer that they choose a username first, then you could use Cloud Functions for Firebase with an HTTP trigger, and pass the username as part of the request. The request would include a query of the given username and the response would return whether the username is available or not. It could look something like this:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.uniqueUsername = functions.https.onRequest((req, res) => {
    const username = req.query.username
    admin.database().ref('users').orderByChild('username').equalTo(username)once('value').then(snap => {
        // if the child exists, then the username is taken
        if (snap.exists()) {
            res.send('username not available');
        } else {
            res.send('username available');
        }
    })   
}


来源:https://stackoverflow.com/questions/44932638/proper-way-to-maintain-unique-usernames-and-extra-profile-data-in-firebase

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