【发布时间】:2021-02-12 12:58:08
【问题描述】:
我对 nodejs 很陌生。目前,我正在将一个值递增到一个数组对象中。编写此代码后出现错误。我想增加linkview 的值。我发现了与我的问题Mongoose - Increment a value inside an array of objects 类似的东西,但我仍然无法解决它。请帮忙
所以这是User 架构
{
"_id": "67324b2cc6817758118e9557d8",
"name": "James",
"__v": 0,
"affiliatelink": [
{
"storeId": 60014d6e7286763490c3543,
"storeName": white choc,
"linkview": 1
}
]
}`
这是我的代码,错误是MongoError: The positional operator did not find the match needed from the query
Admin.findByIdAndUpdate({ _id: adminId }, {$inc: {"affiliatelink.$.linkview": 1}}, function(err, result) {
console.log("ni error "+err)
//if (err) return next(err)
});
【问题讨论】:
-
如果您想在所有对象的
linkview中增加数字,请尝试{ "affiliatelink.$[].linkview": 1 } -
正如@turivishal 所说,使用所有位置运算符
$[]应该可以工作。检查documentation 和一个例子here -
如果您正在使用猫鼬,请确保您已将
adminId转换为对象 ID 尝试mongoose.Types.ObjectId(adminId) -
非常感谢@turivishal。它现在工作:)
标签: node.js mongodb arrayobject