Cloud Firestore:使用动态密钥更新嵌套对象中的字段 [英] Cloud Firestore: Update fields in nested objects with dynamic key

查看:137
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆