Reputation: 457
I'm trying to add a new field called calories:"" to every record in one of the tables within a specific child called "all"
The idea is loop through each record and do a .update adding the new field.
This is my code so far:
const addCalories = () => {
const recipesRef= firebase
.database()
.ref("Recipes");
recipesRef.on("value", (snapshot) => {
const recipes = snapshot.val();
for (let id in recipes) {
recipesRef.child(id).child("all").update({ calories: "" });
}
});
}
and this is a sample record structure
I'm getting the following error:
Error: Reference.update failed: First argument must be an object containing the children to replace.
To be honest, I'm not even sure if my approach is correct.
Upvotes: 0
Views: 851
Reputation: 598708
This is probably closer to what you want:
recipesRef.once("value", (snapshot) => {
snapshot.forEach((child) => {
child.ref.child("all").update({ calories: 0 });
}
});
The main changes:
once
instead of on
, as you only want to make this change once every time this code executes. Using on
would likely lead to many more updates than needed, and possibly to endless recursion.DataSnapshot.forEach
method, instead of a JavaScript for
loop.0
instead of an empty string. I highly recommend storing numeric values as numbers, instead of strings.Upvotes: 2