Angular2 UID as primary key using Firebase Database

别说谁变了你拦得住时间么 提交于 2019-12-25 08:48:24

问题


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

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