Thooyavan Manivaasakar
Thooyavan Manivaasakar

Reputation: 192

Dynamically assign a key value when writing a new data to firebase realtime database using firebase cloud functions

I wrote a cloud function code to create a record in a collection, I want to assign dynamic value as a sub-collection name to the record am creating. The code is as blow

var mobileNumber = eventSnapshot.child('mobileNumber').val()
usersRef.update({
  mobileNumber: {
    email: eventSnapshot.child('email').val(),
    isUserEnabled: eventSnapshot.child('isUserEnabled').val(),
    name: eventSnapshot.child('name').val()
  }
});

The record added to the collection

mobileNumber: {
 email: "[email protected]",
 isUserEnabled: true,
 name: "YYYYYYYYYY"
}

but what I meant to get was a record like the one below

+919876543210: {
 email: "[email protected]",
 isUserEnabled: true,
 name: "YYYYYYYYYY"
}

Upvotes: 1

Views: 155

Answers (1)

Rosário P. Fernandes
Rosário P. Fernandes

Reputation: 11326

Use child() to access the key under the usersRef. And then update the value under that key:

var mobileNumber = eventSnapshot.child('mobileNumber').val()
usersRef.child(mobileNumber).update({
    email: eventSnapshot.child('email').val(),
    isUserEnabled: eventSnapshot.child('isUserEnabled').val(),
    name: eventSnapshot.child('name').val()
});

Upvotes: 1

Related Questions