如何增加嵌套的动态值?

我有一个松散创建的数据库,它有一个名为website. 在这个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);

    }

});

但这不起作用,它给我一个错误,说“错误:'website.[动态网站名称].$inc'中的美元($)前缀字段'$inc'对存储无效。”


我尝试将 $inc 放在其他几个地方,但我得到了相同的信息。


德玛西亚99
浏览 102回答 1
1回答

蝴蝶不菲

当你想引用嵌套字段时,你应该使用点表示法,这样你的 JS 代码应该如下所示:let query = { name: "google.com", like: "huge", follow: "big" };let update = {   $inc: {      [`website.${query.name}.count`]: 1,      [`website.${query.name}.like.${query.like}`]: 1,                     [`website.${query.name}.follow.${query.follow}`]: 1   }}console.log(update);你可以试试看是否有效。问题是您使用点作为子文档名称(google.com, facebook.com)。问题是 MongoDB 是否能够识别该键名google.com而不是{ google: { com: ... } }. 我建议从字段名称中删除这些点。您可以使用下划线而不是点状google_com- 这样会更安全。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript