且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Firebase 中设置用户自己的密钥

更新时间:2023-12-01 23:33:40

当您存储用户数据时,您通常希望键入 uid.毕竟 uid 已经是唯一的,使用 is 作为键可以确保您永远不会有两个节点用于相同的 uid.

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.

当您调用 $add 时,它会为您存储的对象生成一个新的所谓推送 ID.当您有数据列表时,这很好,但在这种情况下,您的数据结构更像是映射:您将 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.

所以解决方案是不调用$add,而是:

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);
});

请注意,这仅使用常规的 Firebase JavaScript SDK,它将与您可能已经拥有的数据的任何 AngularFire 侦听器.

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.