Michel
Michel

Reputation: 11749

Pre-decided keys in realtime database

When using a realtime database, I can create a new record like this:

let newRecord = dbReference.push();
newRecord.set({myField:myFieldValue,myOtherField:myOtherFieldValue});

.push() creates a new record with an automatically generated key.

And this works. But there are cases where one wish to decide the key to be used, rather than have it automatically generated.

What is the proper way to do that?

Upvotes: 0

Views: 31

Answers (1)

Saccarab
Saccarab

Reputation: 1521

const newRecordKey = dbReference.push().key;
dbReference.child(newRecordKey).set({
  myField: myFieldValue,
  myOtherField: myOtherFieldValue
})

If you are looking to access the reference key that is automatically generated you can do this, otherwise, you could initialize newRecordKey with the value you prefer and that should be the object key.

Upvotes: 1

Related Questions