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?

1

1 Answer 1

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) {...}
);
Sign up to request clarification or add additional context in comments.

2 Comments

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
How to look for skills._id not in [1, 2, 3]. Tried {'skills._id': {$nin: [1, 2, 3]}} but didn't work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.