在嵌套对象 Firestore Android 中添加新字段

Asi*_*taq 7 java android firebase google-cloud-firestore

Firestore 文档中有更新嵌套对象字段的代码,但没有关于如何在嵌套对象中添加新字段的代码或文档?

// 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"
        );
Run Code Online (Sandbox Code Playgroud)

正如您在这里看到的,我们正在更新favorites.colorto Red,但是我们如何codefavorites对象中添加新字段?

假设我想更新上述文档如下:

{
  name: "Frank",
  favorites: { food: "Pizza", color: "Blue", subject: "recess", code:32 }
  age: 12
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*amo 8

如果文档确实存在,如果您指定数据应像这样合并到现有文档中,则其内容不会被新提供的数据覆盖:

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());
Run Code Online (Sandbox Code Playgroud)