Butri
Butri

Reputation: 457

Adding an extra field to all records in Firebase Realtime database

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

enter image description here

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

Answers (1)

Frank van Puffelen
Frank van Puffelen

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:

  • Use 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.
  • Loop over the results with the built-in DataSnapshot.forEach method, instead of a JavaScript for loop.
  • Set the value to a numeric 0 instead of an empty string. I highly recommend storing numeric values as numbers, instead of strings.

Upvotes: 2

Related Questions