如何在mongodb中更新数组中的值

时间:2019-06-26 18:33:14

标签: javascript node.js mongodb

我正在尝试更新数组中的值

{
_id: "5d0b939f1f0cc14f83153c43"
categoryName: "Email"
client: "5cff60a4b8b1490049e8325b"
notes: ["note to be updated"]
}

const updateNoteInNoteCategory = async (Id, newNote, index) => {
  const updatedNote = await Note.findByIdAndUpdate(
   { _id: Id },
   { $set: { notes[index]: newNote } },
   { new: true }
  );
}

我正在传递要更新的字段索引,但似乎无法正常工作。

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:0)

您应该尝试通过点符号传递索引,例如:

{$set: {notes.index : newNote}}

请看看to this.

答案 1 :(得分:0)

如果我明白了,我认为当您使用{ notes[0]: newNote }时,您可能会得到{ 'note to be updated': newNote }。 (我尝试过,它无效)

也许您应该尝试{ 'notes.0': newNote }

答案 2 :(得分:0)

您需要使用$来获取notes中正确的元素索引,并传递一些参数以在find中找到要更新的元素,这是一个示例

Notes.updateOne({
    _id: Id,
    'notes': 'note to be updated'
}, {
    $set: {
        'notes.$': 'note updated'
    }
})

答案 3 :(得分:0)

您可以尝试为数组传递点符号。

  

db.arraycheck.update({},{$ set:{“ notes.0”:“更新后检查”}})   WriteResult({“” nMatched“:1,” nUpserted“:0,” nModified“:1})

     

db.arraycheck.find()   {“ _id”:“ 5d0b939f1f0cc14f83153c43”,“ categoryName”:“电子邮件”,“客户端”:“ 5cff60a4b8b1490049e8325b”,“注释”:[“更新后检查”]}