我有一个松散创建的数据库,其中有一个名为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}
}
}
所以网站最初是一个空对象,发生的次数越多,就会添加更多随机网站(例如 google、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 放在其他几个地方,但我收到了相同的消息。
有什么想法吗? :(
最佳答案
当您想要引用嵌套字段时,您应该使用点表示法,这样您的 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
这样的点 - 这样会更安全。
关于javascript - 如何增加嵌套的动态值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60894707/