Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 264
DianeH Avatar asked Dec 02 '14 22:12

DianeH


People also ask

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades.

How do I update nested objects?

To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.

How do you update an array of objects in MongoDB?

Update Documents in an ArrayThe positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator.


1 Answers

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) {...}
);
like image 110
JohnnyHK Avatar answered Oct 03 '22 12:10

JohnnyHK