问题
The question is asked already here, but since AngularFire updates their API, the provided solution is not usable anymore.
What I am doing is to create new user's account with email/password, store that user in Firebase Authentication service, and store extra information in the database.
However, in the Authentication, user has their key as simplelogin:29
, and in the Data, each user has their hashed key, as -JpwB9oUVkeT_XRdiX2V
. I do need their keys to be the same.
Below is the code to create new user, registered with auth.$createUser and store extra information in the user model.
var ref = new Firebase('https://myapp.firebaseio.com/');
var auth = $firebaseAuth(ref);
auth.$createUser({
email: user.email,
password: user.password
}).then(function(regUser) {
var ref = new Firebase('https://myapp.firebaseio.com/users/')
var firebaseUser = $firebaseArray(ref);
var userInfo = {
key : regUser.uid, // ex: simplelogin:29
date : Firebase.ServerValue.TIMESTAMP,
firstname : user.firstname,
lastname : user.lastname,
email : user.email,
}; // user info
firebaseUser.$add(userInfo);
});
It works, but not the way supposed to be, as a user's key in Authentication and Data are still different.
回答1:
When you're storing user data, you typically want to key on uid
. After all the uid
is already unique and using is as the key ensures that you'll never end up with two nodes for the same uid
.
When you call $add
it generates a new so-called push ID for the object that you're storing. This is great when you have lists of data, but in this case your data structure is more map like: you map uid
to the user info.
So the solution is to not call $add
, but instead:
var ref = new Firebase('https://myapp.firebaseio.com/');
var auth = $firebaseAuth(ref);
auth.$createUser({
email: user.email,
password: user.password
}).then(function(regUser) {
var ref = new Firebase('https://myapp.firebaseio.com/users/')
var userInfo = {
key : regUser.uid, // ex: simplelogin:29
date : Firebase.ServerValue.TIMESTAMP,
firstname : user.firstname,
lastname : user.lastname,
email : user.email,
}; // user info
ref.child(regUser.uid).set(userInfo);
});
Note that this just uses the regular Firebase JavaScript SDK, which will interact totally fine with any AngularFire listeners you may already have on the data.
回答2:
You can also try something like this:
var empsRef = ref.child("http://sample.com/employees");
empsRef.child('11111').set({
lastname: "Lee",
firstname: "Kang"
});
empsRef.child('22222').set({
lastname: "Nut",
firstname: "Dough"
});
The output should look like this:
"employees" : {
"11111" : {
"lastname" : "Lee",
"firstname": "Kang"
},
"22222" : {
"lastname" : "Nut",
"firstname": "Dough"
}
}
来源:https://stackoverflow.com/questions/30400890/setting-users-own-key-in-firebase