【问题标题】:update a field in a array inside another array in mongoose document更新猫鼬文档中另一个数组内的数组中的字段
【发布时间】:2021-10-17 02:51:43
【问题描述】:
process = {
  num: 1,
  notes: [ 
    { sequence: 1,
      user: 199283,
      votes: [
         {_id: 113222, user: 122334, text: 'something' },
         {_id: 441122, user: 123321, text: 'other something' },
      ]}, 
    { sequence: 2,
      user: 199213,
      votes: [
         {_id: 111122, user: 121564, text: 'something2' },
         {_id: 222221, user: 126621, text: 'other something2' },
         {_id: 333333, user: 123321, text: 'other something2' }
      ]}
  ]
}

需要在子数组投票中使用_id = 333333 更新字段text

我尝试使用 Model.findAndUpdate()。但是,我在互联网示例中找到了使用 1 级数组进行更新的示例。

如何使用 mongoose 更新文档中另一个数组中的数组中的字段?

【问题讨论】:

    标签: node.js arrays express mongoose subdocument


    【解决方案1】:

    找到文档后,您可以对对象进行任何更改,然后在文档上调用.save() 以在数据库中进行相同的更改。我使用了 forEach 回调,但您也可以使用 lodash 之类的库来更改文本。

    let document = await Model.find({_id:2134315})
    
    document.notes.forEach((note)=>{
      note.votes.forEach((vote)=>{
        if(vote._id==333333) vote.text="YOUR NEW TEXT HERE"
      })
    })
    
    document.save()
    

    如果您使用填充的引用,但从您描述的内容来看,这可能不起作用。

    【讨论】:

      猜你喜欢
      • 2016-04-23
      • 1970-01-01
      • 2021-06-30
      • 2018-12-08
      • 2017-05-26
      • 2012-02-15
      • 2015-04-21
      • 2022-08-18
      • 2020-08-02
      相关资源
      最近更新 更多