问题
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