问题描述
我对 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)
});
解决方法
您需要在对象数组 affiliateLink
您可以使用以下查询并试一试:
Admin.findOneAndUpdate(
{
_id: adminId,"affiliateLink.storeId": "60014d6e7286763490c3543"
},{
$inc: {
"affiliateLink.$.linkView": 1
}
},function(err,result) {
console.log("ni error "+err)
//if (err) return next(err)
});