简体   繁体   中英

Overwrite data without generating new key/node

I'm trying to overwrite some data in my database. The structure is simple, being:

recipes {
  user_1{
    recipe_1{data}
    recipe_2{data}
  }
  user_2{
    recipe_1{data}
    recipe_2{data}
  }
}

I'm trying to update an item and overwrite it with any changes using this, where recipe is the new object with the updated data I'm trying to save, and key is the unique key generated for each item in the database. In the database itself the labels recipe_1 and so on would be replaced with their unique keys. So this path should be just replacing the entire recipe_2 instead of adding a new node.

firebase.database().ref('recipes/' + userID + "/" + key).set({ recipe });

So say I was attempting to update user_1's recipe_2 with this, after going through, the database structure would then be:

data {
  user_1{
    recipe_1{data}
    recipe{
      recipe_2{data}
    }
  }
  user_2{
    recipe_1{data}
    recipe_2{data}
  }
}

How can I overwrite the item and keep the structure of the database the same while changing the contents of the recipe?

You need to remove the extra {} from your set function which is creating a new node in the key value you are trying to update.

Change your code to
firebase.database().ref('recipes/' + userID + "/" + key).set(recipe);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM