我想使用索引替换数组中的对象,但什么都不会保存。这就是文档的样子:
{
"_id": {
"$oid": "58a71ec0c80a9a0436ae2fb1"
},
"owner": "contact1@gmail.com",
"contacts": [
{
"work": "",
"home": "",
"mobile": "",
"email": "",
"company": "",
"last": "Contact",
"middle": "",
"first": "New"
},
{
"first": "Another",
"middle": "",
"last": "Contact",
"company": "",
"email": "",
"mobile": "",
"home": "",
"work": ""
}
],
"__v": 1
}
这就是我尝试过的......
Contacts.findById({_id: "58a71ec0c80a9a0436ae2fb1"}, function(err,document) {
document.contacts[req.body.indexOfObjectToBeEdited] = req.body.updatedObject
console.log(document)
document.save(function(err) {
return res.json({event:"Updated Contact"})
})
})
在document.save()之前,我是console.log(文档),它反映了正确的更改。但是当我保存时,mongodb中没有更新任何内容,我没有收到任何错误。我应该做些什么?
答案 0 :(得分:2)
尝试在保存之前插入此行。由于修改数组需要手动告诉mongoose它被修改。
document.markModified("contacts");
查看文档中的使用说明以获取更多信息 http://mongoosejs.com/docs/schematypes.html