我在this question中遇到了类似的问题,但是我在另一个方面绊脚石。我在mongo数据库的文档中嵌入了一系列对象/子文档,像这样的架构...。
const projectSchema = new mongoose.Schema({
name: {
type: String
},
...
stakeholders: [{
stakeholderTitle: {
type: String,
max: 150,
required: [true, 'A stakeholder must have a title.']
},
...
}],
我需要做的是基于查询更新特定的嵌入式对象,但是我仍然需要返回父文档。基于对this question的回答,我能够使用子文档的ID检索父文档,但是当我尝试更新子文档时,我无法弄清楚。这是我的查询
const filter = { 'stakeholders._id': req.body.stakeholderId }
const update = { stakeholderTitle: req.body.stakeholderTitle } // suspect the problem is here
let project = await Project.findOneAndUpdate(filter, update, {
new: true,
runValidators: true
})
这将按预期方式获取父文档,并且我假设我的“ update”参数是问题所在,但我不确定是否在基于ID的查询已“查找”时如何更新我想要,但不是“更新”。
答案 0 :(得分:1)
您的update
语句期望stakeholderTitle
位于文档的根目录下。要正确定义路径,您必须使用$ positional operator:
const update = { 'stakeholders.$.stakeholderTitle': req.body.stakeholderTitle }