Update a field in an object in Firestore?

2020-07-02 10:57发布

问题:

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.

回答1:

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