问题
Im creating a signup component in my app using Firebase as Auth method and Database. When I register a new user, a key is generated and then I save all the user info including the UID from authentication in my database. What I want to do is to use UID from authentication as my primary key instead of the key generated by Firebase.
This is my code:
component.ts
signupUser(user: User) {
this.firebaseAuth.auth
.createUserWithEmailAndPassword(user.email, user.password)
.then(value => {
console.log('Success!', value);
this.afdb.list('users').push({
firstname: user.firstname,
lastname: user.lastname,
email: user.email,
uid: value.uid
});
})
.catch(err => {
console.log('Something went wrong:',err.message);
});
}
json in Firebase
users {
-KpgNYJ0adjVyOGJiyBF {
email: test@test.com
firstname: dasdsa
lastname: dsadsads
uid: 021oxk8X6rQL6gAfC0UhZpB4vZx2
}
}
What I want
users {
021oxk8X6rQL6gAfC0UhZpB4vZx2 {
email: test@test.com
firstname: dasdsa
lastname: dsadsads
}
}
Your help is deeply appreciated as always. Thanks.
EDIT: I forgot to tell Im using AngularFire2.
回答1:
Use update
instead of push
. push
creates a new node and a unique key for that node. While update
updates the specified node, or creates it if it doesn't already exist.
signupUser(user: User) {
this.firebaseAuth.auth.createUserWithEmailAndPassword(user.email, user.password)
.then(value => {
console.log('Success!', value);
let userDetails = {
firstname: user.firstname,
lastname: user.lastname,
email: user.email
}
this.afdb.list('users').update(value.uid, userDetails);
})
.catch(err => {
console.log('Something went wrong:',err.message);
});
}
来源:https://stackoverflow.com/questions/45260292/angular2-uid-as-primary-key-using-firebase-database