有我的代码:
var fileModel = context.models.File,
query = {
_id: context.models.ObjectId("532083358ab1654c0c8b4ced") // TODO: for debug, change after update fix
},
update = {
description: context.data.description,
userId: context.data.userId ?
context.models.ObjectId(context.data.userId) : undefined,
isAdded: true
};
fileModel.update(query, update, { multi: true }, function (err) {
if (err) {
console.log('update');
console.log(err);
context.sendJson({ success: false, err: err });
}
else {
context.sendJson({ success: true });
}
});
有我的架构:
var fileSchema = new schema({
path: { type: String, required: true, validate: [validateName, 'a path is required'] },
isApproved: { type: Boolean, default: false },
isAdded: { type: Boolean, default: false },
name: { type: String, required: true, validate: [validateName, 'a name is required'] },
description: { type: String },
userId: { type: schema.Types.ObjectId },
updated: { type: Date, default: Date.now },
size: { type: Number }
}, { autoIndex: false });
当我尝试按ID更新文档时,我在控制台中看到此消息:
update
[TypeError: Cannot read property '_id' of undefined]
我认为问题在
userId: context.data.userId ?
context.models.ObjectId(context.data.userId) : undefined,
但我不明白如何解决它。
答案 0 :(得分:0)
我通过代码的单独部分解决了这个问题。但我无法理解我的第一个解决方案中的错误。那个工作代码:
var fileModel = context.models.File,
query = {
_id: {
$in: context.data.files.map(function (el) {
return context.models.ObjectId(el);
})
}
},
update = {
description: context.data.description,
isAdded: true
};
if (context.data.userId){
update.userId = context.models.ObjectId(context.data.userId);
}
fileModel.update(query, update, { multi: true }, function (err) {
if (err) {
console.log('update');
console.log(err);
context.sendJson({ success: false, err: err });
}
else {
context.sendJson({ success: true });
}
});