Mongoose MongoDB: updating objects in a nested array

I’ve got the following schema

var UserSchema = new Schema({
  emp_no: Number,
  skills: [{
    skill: {
      type: Schema.Types.ObjectId,
      ref: 'Skill'
    },
    startDate: {type: Date},
  }]
});

I’m then trying to update the startDate of one particular skill. I’ve tried several differents ways, one of them being:

User.findOne({emp_no: req.body.emp_no}, function (err, user) {
    user.update( {'skills._id': 123}, {'$set': {
        'skills.$.startDate': req.body.startDate          
    }}
}

This particular code gives: err: ‘cannot use the part (skills of skills._id) to traverse the element

The actual object looks like

{
"_id" : ObjectId("5469753de27a7c082203fd0a"),
"emp_no" : 123,
"skills" : [ 
    {
        "skill" : ObjectId("547d5f3021d99d302079446d"),
        "startDate" : ISODate("2014-12-02T06:43:27.763Z")
        "_id" : ObjectId("547d5f8f21d99d3020794472")
    }
],
"__v" : 108

}

Any ideas what I’m doing wrong?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

When you call update on a model instance like you’re doing here, the first parameter is the update operation to apply to that document, as the document to update is already uniquely identified by its _id.

Instead, use Model.update to do this all in one operation:

User.update(
    {emp_no: req.body.emp_no, 'skills._id': 123}, 
    {'$set': {
        'skills.$.startDate': req.body.startDate          
    }},
    function(err, numAffected) {...}
);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply