8

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?

DianeH
  • 247
  • 1
  • 3
  • 12

1 Answers1

17

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) {...}
);
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Thanks a lot, this works! I had tried it in the past by I guess something else has been wrong so didn't get the right results – DianeH Dec 03 '14 at 02:53
  • How to look for `skills._id` not in `[1, 2, 3]`. Tried `{'skills._id': {$nin: [1, 2, 3]}}` but didn't work. – Rahil Wazir Jul 01 '15 at 16:57