【发布时间】:2020-05-20 15:22:41
【问题描述】:
我在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
})
这会按预期获取父文档,并且我假设我的“更新”参数是问题所在,但是当我的查询已经基于 id 进行“查找”时,我不完全确定如何更新我想要,但不是“更新”。
【问题讨论】: