문제

How can I update an embedded document that is more than one level deep by using the _id of the item I wish to update?

For example, if I have the following in my model file:

var Subitems = new Schema({
  "title": String,
  "body": String
)}

var Items = new Schema({
  "title": String,
  "subitems": [Subitems]
)};

var Projects = new Schema({
  "title": String,
  "description": String,
  "items": [Items]
});

var exports = module.exports = mongoose.model('Project', Projects);

How would I go about updating the body of one of my subitems where I know the _id of the subitems element?

I assume I would first find the Project (easy enough), and then push to the subitems and save the Project. So the question is, how do you push to a more than one level deep embed without having to iterate through everything above it? Can I do it by its _id ?

도움이 되었습니까?

해결책

Ok, I think I just figured it out. Funny how that always happens right after posting to SO :)

Here's what I did, let me know if there's any better/different way:

var myitem  = req.project.items.id(item_id);
myitem.body = req.body.item.body;

req.project.save(function (err){
  //woohoo! updated the embedded doc with the new values!      
});

I figured it out by following the advice in the selected answer in this SO post: How to update embedded document in mongoose?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top