Javascript 如何增加嵌套的动态值?

Javascript 如何增加嵌套的动态值?,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我有一个松散创建的数据库,它有一个名为website的键。在这个网站对象中,我将有多个对象,每个动态创建的网站一个。数据库的外观示例如下: website: { google.com: { count: 19, like: {huge: 9, normal: 10}, follow: {big: 11, small: 8} }, facebook.com: { count: 1, like:

我有一个松散创建的数据库,它有一个名为
website
的键。在这个
网站
对象中,我将有多个对象,每个动态创建的网站一个。数据库的外观示例如下:

website: {
    google.com: {
        count: 19,
        like: {huge: 9, normal: 10},
        follow: {big: 11, small: 8}
    },
    facebook.com: {
        count: 1,
        like: {huge: 1},
        follow: {big: 1}
    }
}
因此,网站最初是一个空对象,发生的事情越多,随机添加的网站就越多(谷歌、facebook就是一个例子)

现在,当我点击这些值时,我希望里面的值增加1,例如

User.findByIdAndUpdate({"_id": id}, {
website: {
    [query.name]: { $inc : { //query.name is the dynamic name that'll be given
        count: 1, //I want this count value incremented by one
        like: {
            [query.like]: 1 //query.like would be either huge or normal or something that's not available yet, in which case it would be created with a value of 1. If it exists I want the value incremented by one.
        },
        follow: {
            [query.follow]: 1 //query.follow would be either big or small or something that's not available yet, in which case it would be created with a value of 1. If it exists I want the value incremented by one.
        }
    }}
}
}, function(err, result){
    if (err) {
        console.log(err);
    } else {
        console.log(result);
    }
});
但这不起作用,它会给我一个错误,提示“错误:网站中以美元($)为前缀的字段“$inc.$inc.$inc.$inc”对存储无效。”

我试着把$inc放在其他一些地方,但我得到了大致相同的信息


有什么想法吗(

当您想要引用嵌套字段时,您应该使用点符号,因此您的JS代码应该如下所示:

let query={name:“google.com”,如:“巨大”,跟随:“巨大”};
让更新={
$inc:{
[`website.${query.name}.count`]:1,
[`website.${query.name}.like.${query.like}`]:1,
[`website.${query.name}.follow.${query.follow}`]:1
}
}

console.log(update);
非常感谢,这非常有效!我还记得去掉点,因为正如您所说,mongo肯定无法区分。再次感谢!)