Adam Goldberg
Adam Goldberg

Reputation: 223

Key being returned from database is different to the one shown

I am trying to get the key that is generated by Firebase database when an Item is pushed to the database, however, the key being returned is of a different value. In the photo, you can see that the value for 'key' (-kqI0bxKg...) is different to that of the pushed object primary key. Why is a different key being returned (-kql0bxKgq...)? How do I fix this using angularfire and typescript?

  handler: data => {
    this.afAuth.authState.subscribe(auth => {
        const currentUser = auth.uid;
        var myRef = this.afDatabase.database.ref().push()
        var myKey = myRef.key;
        console.log(myKey);
        var newEntry = {
            description: data.description,
            number: 0,
            createdBy: currentUser,
            key: myKey
        }
        this.afDatabase.list('whatIWant').push(newEntry);
    })
  }

Firebase database

Upvotes: 1

Views: 30

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Every time you call push() a new ID is generated. Since you're calling push() in two places in your code, you're generating two separate IDs. To have the same ID in both places, call push() once and use the new reference in both places:

    var myRef = this.afDatabase.database.ref().push()
    var myKey = myRef.key;
    ...
    myRef.set(newEntry);

Upvotes: 1

Related Questions