Mongoose FindOneAndUpdate an embedded object and return parent

会有一股神秘感。 提交于 2021-02-11 04:21:56

问题


I'm having a similar problem laid out in this question, but I'm stumbling on a different aspect. I have an array of objects/subdocuments embedded within a document in my mongo database, schema like this....

const projectSchema = new mongoose.Schema({
   name: {
      type: String
   },
  ...
   stakeholders: [{
    stakeholderTitle: {
        type: String,
        max: 150,
        required: [true, 'A stakeholder must have a title.']
        },
        ...
    }],

what I need to do is update a particular embedded object based on the query, but I still need to then return the parent document. Based on an answer to this question, I was able to retrieve the parent document using the id for the subdocument, but when I then try and update the subdocument, I can't figure it out. This is my query

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
})

This fetches the parent document as intended, and I'm assuming that my 'update' argument is where the problem is, but I'm not entirely sure how to update when my query is already 'finding' based on the id I want, but not 'updating'.


回答1:


Your update statement expects stakeholderTitle to be on a root level of your document. To define the path correctly you have to use the $ positional operator:

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


来源:https://stackoverflow.com/questions/60063481/mongoose-findoneandupdate-an-embedded-object-and-return-parent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!