Cloud Firestore:使用动态键更新嵌套对象中的字段 [英] Cloud Firestore: Update fields in nested objects with dynamic key
本文介绍了Cloud Firestore:使用动态键更新嵌套对象中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
遵循firestore的官方文档:
following the official documentation of firestore :
{
name: "Frank",
favorites: { food: "Pizza", color: "Blue", subject: "recess" },
age: 12
}
// To update favorite color:
db.collection("users").doc("frank").update({
"favorites.color": "Red"
})
我想使用动态键而不是颜色.
I would like to use a dynamic key instead of color.
db.collection("users").doc("frank").update({
"favorites[" + KEY + "].color": true
});
这当然是不可能的,并且会抛出错误.
this is of course not possible and will throw an error.
我一直在尝试这样做:
db.collection("users").doc("frank").update({
favorites: {
[key]: {
color": true
}
}
});
它实际上是用正确的键更新,但不幸的是,它覆盖了其他键(它们正在被删除).
It is actually updating with the right key but unfortunately, it is overwriting the other keys (they are being deleted).
推荐答案
我找到了灵感来自 firebase 解决方案的解决方案(将/"替换为.").
I found the solution inspired by a firebase solution (replacing "/" by ".").
var usersUpdate = {};
usersUpdate[`favorites.${key}.color`] = true;
db.collection("users").doc("frank").update(usersUpdate);
这篇关于Cloud Firestore:使用动态键更新嵌套对象中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文