packability
packability

Reputation: 384

Update a field in an object in Firestore?

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.

Upvotes: 26

Views: 42983

Answers (2)

nashihu
nashihu

Reputation: 849

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"
});

Upvotes: 1

Shawn Lauzon
Shawn Lauzon

Reputation: 6282

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" }

Upvotes: 46

Related Questions