【问题标题】:Mongoose FindOneAndUpdate an embedded object and return parentMongoose FindOneAndUpdate 嵌入对象并返回父对象
【发布时间】: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 进行“查找”时,我不完全确定如何更新我想要,但不是“更新”。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您的update 语句要求stakeholderTitle 位于文档的根级别。要正确定义路径,您必须使用$ positional operator:

    const update = { 'stakeholders.$.stakeholderTitle': req.body.stakeholderTitle }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      • 2017-03-08
      相关资源
      最近更新 更多