Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 853
packability Avatar asked Jan 01 '18 01:01

packability


People also ask

How do I update a field in firestore?

Firestore Update Document Field What if we want to just update a value of a specific field in an existing document. To do that, all we have to do is add a third argument to the setDoc() method. It will be a JavaScript object with a single property: merge:true.

How do I increment a field in firestore?

Firestore now has a specific operator for this called FieldValue. increment() . By applying this operator to a field, the value of that field can be incremented (or decremented) as a single operation on the server.


1 Answers

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" }
like image 81
Shawn Lauzon Avatar answered Oct 20 '22 07:10

Shawn Lauzon