24

This is the example provided in the documentation to update a field within a nested object in firebase.

var frankDocRef = db.collection("users").doc("frank");
frankDocRef.set({
name: "Frank",
favorites: { food: "Pizza", color: "Blue", subject: "recess" },
age: 12
});

// To update age and favorite color:
db.collection("users").doc("frank").update({
"age": 13,
"favorites.color": "Red"
})
.then(function() {
console.log("Document successfully updated!");
});

Instead of updating the favourites, I want to add to favourites would someone point me in the right direction on how to do this.

Let's say I want to

firebase: "Help"
the the resulting favourites object should be
favorites: { food: "Pizza", color: "Blue", subject: "recess", firebase: "Help" },

I used set with the dot operation but it overrides everything instead.

2 Answers 2

45

To add an entry to a set (a Javascript Object), use DocumentReference.update:

db.collection("users").doc("frank").update({
  "favorites.firebase": "Help")}
})

will result in

favorites: { food: "Pizza", color: "Blue", subject: "recess", firebase: "Help" }
3
  • 2
    Anyway we can do this dynamically? say favorites.someUid? Aug 27, 2018 at 22:01
  • 9
    You could use templateStrings. const update = {};. Then set update fields like this update[`favorites.${someUid}`] = 'abc'; and update the collection db.collection("users").doc("frank").update(update)
    – Vispercept
    Dec 11, 2018 at 9:34
  • @Vispercept I have a case like let update_id = { department:{ } } , now I want to add new data inside the department object. how to update the department map without getting the previous value? Aug 31 at 19:07
1

in case someone looking for latest update for 2023, i got from here

import { doc, updateDoc } from "firebase/firestore";

const userRef = doc(db, "users", "frank");

await updateDoc(userRef, {
    "favorites.color": "Red"
});

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.