【问题标题】:Trying to update a property in an object inside array of arrays mongodb with node js尝试使用节点 js 更新数组 mongodb 内的对象中的属性
【发布时间】:2022-01-05 09:16:51
【问题描述】:

我在另一个数组中的数组中有一个对象... 我如何通过他的 id 更新某个玩家的“积分”属性? db structure image

试过了,还是不行……

 let h2h=await H2h.find({"players.$.id":req.params.id})
 let h2h = await H2h.updateMany(
   { "players.$.id": req.params.id},
   { $set: { "players.$": user} },
   {
     new: true,
   }
 );

【问题讨论】:

  • 究竟是什么不起作用?它会引发错误吗?它是否修改了某些内容但不是您想要的值?
  • 它不起作用,即对象中的任何属性都没有更新......我猜是因为我没有找到元素的正确位置

标签: node.js reactjs mongodb


【解决方案1】:

您实际上并不需要第一个 let h2h = await H2h.find(.....,因为您已经在 updateMany 方法中“查找并更新”了文档。

要更新特定玩家的属性points,您真的很接近解决方案,numberOfPointsGiven 是您要更新它的数字:

let h2h = await H2h.updateMany(
   { "players.$.id": req.params.id},
   { $set: { "players.$.points": numberOfPointsGiven} }
 );

请记住,updateMany不会返回新编辑的对象,因为它不同于 findByIdAndXfindOneAndX。相反,它会返回一个查询,指示已更新了多少文档等。请阅读更多here

【讨论】:

    【解决方案2】:

    我实际上想更新“名称”属性(“点”是一个错误) 正确答案是:

     let h2h=await H2h.updateMany(
    //this line targets the element inside the array thats inside another array
        {"players":{$elemMatch:{$elemMatch:{id:req.params.id}}}},
    //this line sets the 'name' property inside the unnamed array thats inside the players array
        { $set: { "players.$[].$[elem].name": user.nickName } },
    //this line is for mongo to update only the element that matches the user's id
        {arrayFilters:[{'elem.id':req.params.id}]},
    

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 2023-01-31
      • 2020-10-29
      • 2021-11-19
      相关资源
      最近更新 更多