1
votes

I have been storing all my users in my firebase database using the push() method. This method generates a unique id for each user and stores them under this id. I am trying to change this so that my users are stored under a user.uid that is auto generated as well when you use the set() method, however, I'm having trouble storing them under this user uid.

I am using the following to add users to the database, what am I missing here?

firebase.database().ref().child('accounts').set({
                email: user.email,
                userId: firebase.auth().currentUser.uid

              })

this uses set() and stores the data like this:

{
  "accounts" : {
      "email" : "",
      "userId" : ""
    },
{
      "email" : "",
      "userId" : ""
    }
}

Using push() the structure looks like this: The users are stored based on the firebase generated push Id.

{
  "accounts" : {
    "-KRPSyO4B48IpBnHBTYg" : {
      "email" : "",
      "userId" : ""
    },
    "-KR4f4s5yvdr67g687nrth" : {
      "email" : "",
      "userId" : ""
    }
  }

What I'm looking for is this structure: Users are stored by the firebase generated userId..

{
      "accounts" : {
        "userId value" : {
          "email" : "",
          "userId" : ""
        },
        "userId value" : {
          "email" : "",
          "userId" : ""
        }
      }

Any help would be greatly appreciated!!

1

1 Answers

6
votes

You're not yet creating a node for the uid itself in your path. Change it to:

var uid = firebase.auth().currentUser.uid;
firebase.database().ref().child('accounts').child(uid).set({
  email: user.email,
  userId: uid
})