sunilsmith
sunilsmith

Reputation: 111

Update a single array value of an Nested object in Mongoose

I was trying to update a value in an array using Mongoose and the table I created is given below

var newUser = User({
        name      : 'XXX',
        userName  : 'XXX',
        password  : 'XXX',
        admin     : true,
        location  : 'KKK',
        studentDeatails   : [
            {
                name  : 'AAA',
                study : {
                    dept   : 'CSE',
                    course : 'B.E',
                    year   : 4
                }
            },
            {
                name  : 'BBB',
                study : {
                    dept   : 'EEE',
                    course : 'B.E',
                    year   : 3
                }
            }
        ],
        createdAt: Date(),
        updatedAt: Date()
    });

Result:

[ { _id: 57c42dd22842e7561e8b9612,
    name: 'XXX',
    userName: 'XXX',
    password: 'XXX',
    admin: true,
    location: 'KKK',
    createdAt: 2016-08-29T12:42:58.000Z,
    updatedAt: 2016-08-29T12:42:58.000Z,
    studentDeatails: [ { name: 'AAA',
    _id: 57c42dd22842e7561e8b9614,
    study: { dept: 'CSE', course: 'B.E', year: 4 } },
  { name: 'BBB',
    _id: 57c42dd22842e7561e8b9613,
    study: { dept: 'EEE', course: 'B.E', year: 3 } } ] } ]

I was trying to update the value of dept : 'EEE' -> dept: 'MECH'

My expected answer should be :

[ { _id: 57c42dd22842e7561e8b9612,
    name: 'XXX',
    userName: 'XXX',
    password: 'XXX',
    admin: true,
    location: 'KKK',
    createdAt: 2016-08-29T12:42:58.000Z,
    updatedAt: 2016-08-29T12:42:58.000Z,
    studentDeatails: [ { name: 'AAA',
    _id: 57c42dd22842e7561e8b9614,
    study: { dept: 'CSE', course: 'B.E', year: 4 } },
  { name: 'BBB',
    _id: 57c42dd22842e7561e8b9613,
    study: { dept: 'MECH', course: 'B.E', year: 3 } } ] } ]

The code I tried is :

User.findOneAndUpdate(
    { name: 'XXX', 'studentDeatails.study.year': 3 },
    { "$set": { 'studentDeatails.0.study.$.dept' : 'MECH' } },
    function(err){
        if(err){
            console.log(err);
        } else {
            console.log("Successfully Updated");
        }
    }
);

Please correct what I have done wrong using Mongoose, it'll be of great help!

Upvotes: 1

Views: 81

Answers (1)

chridam
chridam

Reputation: 103365

Because study field is a subdocument, no need to apply the positional $ operator as that only works on embedded documents within an array. It should be applied on the studentDeatails (sic) array field. So your update should simply be:

User.findOneAndUpdate(
    { "name": "XXX", "studentDeatails.study.year": 3 },
    { "$set": { "studentDeatails.$.study.dept" : "MECH" } },
    function(err){
        if(err){
            console.log(err);
        } else {
            console.log("Successfully Updated");
        }
    }
);

Upvotes: 2

Related Questions