【问题标题】:Mongoose Nodejs - update array of object with increment valueMongoose Nodejs - 使用增量值更新对象数组
【发布时间】: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


【解决方案1】:

您需要在对象数组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)
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-19
    • 2019-03-25
    • 2019-12-15
    • 2019-08-05
    • 2015-03-28
    • 1970-01-01
    • 2021-07-08
    相关资源
    最近更新 更多