On the Firestore documentation there is code to update the nested object field but there is no code or documentation about how we can add the new field in the nested object?
// Assume the document contains:
// {
// name: "Frank",
// favorites: { food: "Pizza", color: "Blue", subject: "recess" }
// age: 12
// }
//
// To update age and favorite color:
db.collection("users").document("frank")
.update(
"age", 13,
"favorites.color", "Red"
);
As you can see here we are updating the favorites.color
to Red
, but how we can add the new field code
in the favorites
object?
Suppose I want to update the above document as the follows:
{
name: "Frank",
favorites: { food: "Pizza", color: "Blue", subject: "recess", code:32 }
age: 12
}
Build a DocumentReference to the document you want to update, then use the update() method on the DocumentReference to indicate only the fields to be added or changed. Pass it an object with only properties that match the fields to add or change.
If the document does exist, its contents will not be overwritten with the newly provided data if you specify that the data should be merged into the existing document like this:
Map<String, Object> favorites = new HashMap<>();
Map<String, Object> favorite = new HashMap<>();
favorite.put("code", 32);
favorites.put("favorites", favorite);
rootRef.collection("users").document("frank").set(favorites, SetOptions.merge());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With