更新Mongoose中的嵌套对象的单个数组值

我正在尝试使用Mongoose更新数组中的值,下面给出了我创build的表

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() }); 

结果

 [ { _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 } } ] } ] 

我试图更新部门的价值: 'EEE' -> dept: 'MECH'

我的预期答案应该是:

 [ { _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 } } ] } ] 

我试过的代码是:

 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"); } } ); 

请纠正我使用mongoose做错了什么,这将是非常有帮助的!

因为study领域是一个子文档,所以不需要应用位置$操作符,因为它仅适用于数组中的embedded式文档。 它应该应用于studentDeatails (sic)数组字段。 所以你的更新应该是:

 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"); } } );