【问题标题】:Update a field in an object in Firestore?更新 Firestore 中对象中的字段?
【发布时间】:2018-06-11 07:33:55
【问题描述】:

这是文档中提供的示例,用于更新 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!");
});

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

假设我想

firebase: "Help"
the the resulting favourites object should be
favorites: { food: "Pizza", color: "Blue", subject: "recess", firebase: "Help" },

我在点操作中使用了 set,但它会覆盖所有内容。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

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

    db.collection("users").doc("frank").update({
      "favorites.firebase": "Help")}
    })
    

    会导致

    favorites: { food: "Pizza", color: "Blue", subject: "recess", firebase: "Help" }
    

    【讨论】:

    • 无论如何我们可以动态地做到这一点?说 favorites.someUid?
    • 您可以使用模板字符串。 const update = {};。然后像这样设置更新字段update[`favorites.${someUid}`] = 'abc';并更新集合db.collection("users").doc("frank").update(update)
    猜你喜欢
    • 2019-02-13
    • 2021-04-14
    • 1970-01-01
    • 2018-08-15
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    相关资源
    最近更新 更多