Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update firebase with array of objects?

For an example we have the database:

//the database
firebase: {
  1: a,
  2: b,
  3: c
}

//the ref 
var firebaseRef = firebase.database().ref();

//what we need
var change = [
  {
    id: 2,
    value: "y"
  },
  {
    id: 3,
    value: "z"
  },
];

//a possible way how we want
firebaseRef.update({
  change[0].id: change[0].value,
  change[1].id: change[1].value
})

I have a few questions.

The last block needs to loop through the array. But i don't know if it is a good practice to call update repeatedly.

The second important thing is that while the keys above only have one value, it's good, but if it's an object which has a few properties, the only one we want to set will override the other properties. I think the best way to solve this to create a loop with setting the database's child to the array's actual object's id or key, and then update the necessary properties.

But isn't it a bad practice to loop through an array and call the update function repeatedly?

like image 351
Gergő Horváth Avatar asked Feb 28 '26 16:02

Gergő Horváth


1 Answers

There is no harm in calling the update() function repeatedly. All the requests to the database are going over a single connection, so the overhead per call is minimal.

But you might want to do a single update for atomicity: to ensure either all writes are allowed, or none of them are allowed.

Here's one way to do that, by looping over the changes in JavaScript:

var changes = [
  {
    id: 2,
    value: "y"
  },
  {
    id: 3,
    value: "z"
  },
];
var updates = {};
changes.forEach((change) => {
  updates[change.id] = change.value;
});
ref.update(updates);
like image 104
Frank van Puffelen Avatar answered Mar 02 '26 07:03

Frank van Puffelen