【问题标题】:How to update an array with his index number in Mongoose如何在 Mongoose 中用他的索引号更新数组
【发布时间】:2020-12-06 00:46:12
【问题描述】:

我的用户模型有一个带有物品(数组)的购物车。我想检查他的购物车中的每件商品是否有足够的库存,如果没有,则将购物车中的商品数量更新为可用库存(已填充 productId)。

   }                   
})

'cart.items[i].quantity' 太简单了,它不起作用:D

用户: [![在此处输入图片描述][1]][1]

产品: [![在此处输入图片描述][2]][2]

【问题讨论】:

  • 文档长什么样?可以发布一些示例文件。
  • 添加截图(是的,我知道productId不一样,这是一个例子)

标签: node.js mongodb mongoose


【解决方案1】:

这是您提供的代码。

user.cart.items.forEach((item, i) => {
   if (item.quantity > item.productId.stock) {
      User.findByIdAndUpdate(user._id, {'cart.items[i].quantity': item.productId.stock})
   }                   
})

从上面的代码我可以看到我们有要更新的项目的productId。那么当我们有 productId 时为什么要使用索引呢?无论如何,我已经根据您的屏幕截图创建了一个示例文档,并创建了一个查询,该查询基于productId 更新了quantity。您可以转到 mongo playground 链接并运行查询并根据您的需要进行调整。

试试这个查询-

db.collection.update({
  _id: 1
},
{
  "$set": {
    "cart.items.$[element].quantity": 2   /**where 2=item.productId.stock*/
  }
},
{
  arrayFilters: [
    {
      "element.productId": 100
    }
  ]
})

这里是Mongo Playground

编辑:

如果你还想用索引来做。

db.collection.update({
  _id: 1
},
{
  "$set": {
    "cart.items.1.quantity": 2/**where 1 is index and 2=item.productId.stock*/
    
  }
})

这里是playground

【讨论】:

  • 感谢您的支持。我也更新了索引查询的答案。
猜你喜欢
  • 1970-01-01
  • 2018-02-14
  • 2017-05-20
  • 2014-09-07
  • 1970-01-01
  • 2015-09-19
  • 2014-02-18
  • 1970-01-01
  • 2020-10-09
相关资源
最近更新 更多