Mongodb Mongoose FindOneAndUpdate嵌入对象并返回父对象
我在中也遇到了类似的问题,但我在另一个方面遇到了障碍。我在mongo数据库的文档中嵌入了一系列对象/子文档,模式如下Mongodb Mongoose FindOneAndUpdate嵌入对象并返回父对象,mongodb,mongoose,Mongodb,Mongoose,我在中也遇到了类似的问题,但我在另一个方面遇到了障碍。我在mongo数据库的文档中嵌入了一系列对象/子文档,模式如下 const projectSchema = new mongoose.Schema({ name: { type: String }, ... stakeholders: [{ stakeholderTitle: { type: String, max: 150, required: [tr
const projectSchema = new mongoose.Schema({
name: {
type: String
},
...
stakeholders: [{
stakeholderTitle: {
type: String,
max: 150,
required: [true, 'A stakeholder must have a title.']
},
...
}],
我需要做的是根据查询更新一个特定的嵌入对象,但我仍然需要返回父文档。根据对的回答,我能够使用子文档的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“finding”而不是“update”时如何更新 您的
update
语句要求stakeholderTitle
位于文档的根级别。要正确定义路径,必须使用:
const update = { 'stakeholders.$.stakeholderTitle': req.body.stakeholderTitle }