Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new field in nested object firestore Android

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
}
like image 303
Asif Mushtaq Avatar asked May 29 '18 21:05

Asif Mushtaq


People also ask

How do I add a field to an existing document in firestore?

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.


1 Answers

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());
like image 145
Alex Mamo Avatar answered Nov 11 '22 19:11

Alex Mamo