繁体   English   中英

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

[英]how to update a value in an array in 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 }
  );
}

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

任何帮助,将不胜感激。

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

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

并请看一下

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

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

您需要使用$进去正确的元素索引notes ,并通过一些参数来找到你想要的更新元素find ,这里是个例

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

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

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

db.arraycheck.find(){“ _id”:“ 5d0b939f1f0cc14f83153c43”,“ categoryName”:“电子邮件”,“ client”:“ 5cff60a4b8b1490049e8325b”,“ notes”:[更新后的检查“]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM