更新Firestore中对象中的字段?

pac*_*ity 8 javascript firebase google-cloud-firestore

这是文档中提供的用于更新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!");
});
Run Code Online (Sandbox Code Playgroud)

而不是更新收藏夹,我想添加到收藏夹,有人会指出我正确的方向如何做到这一点.

让我们说我想

firebase: "Help"
the the resulting favourites object should be
favorites: { food: "Pizza", color: "Blue", subject: "recess", firebase: "Help" },
Run Code Online (Sandbox Code Playgroud)

我使用set操作但是它会覆盖所有内容.

Sha*_*zon 11

要向集合(Javascript对象)添加条目,请使用DocumentReference.update:

db.collection("users").doc("frank").update({
  "favorites.firebase": "Help")}
})
Run Code Online (Sandbox Code Playgroud)

会导致

favorites: { food: "Pizza", color: "Blue", subject: "recess", firebase: "Help" }
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用模板字符串。`const 更新 = {};`。然后像这样设置更新字段`update[\`favorites.${someUid}\`] = 'abc';` 并更新集合`db.collection("users").doc("frank").update(update )` (6认同)
  • 无论如何我们可以动态地这样做吗?say favorites.someUid? (2认同)