Mongoose MongoDB:更新嵌套数组中的对象
问题描述:
我有以下模式
var UserSchema = new Schema({
emp_no: Number,
skills: [{
skill: {
type: Schema.Types.ObjectId,
ref: 'Skill'
},
startDate: {type: Date},
}]
});
然后,我尝试更新一项特定技能的startDate.我尝试了几种不同的方式,其中一种是:
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
}}
}
此特定代码给出:err:'无法使用零件(skills._id的技能)遍历元素
This particular code gives: err: 'cannot use the part (skills of skills._id) to traverse the element
实际对象看起来像
{
"_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?
答
调用 update
在像您在此处这样的模型实例上,第一个参数是应用于该文档的更新操作,因为要更新的文档已经由其_id
唯一标识.
相反,请使用 Model.update
一次完成所有操作:
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) {...}
);