【发布时间】:2018-03-14 23:55:54
【问题描述】:
我有一个看起来像这样的 Mongoose 架构:
let ChildSchema = new Schema({
name:String
});
ChildSchema.pre('save', function(next){
if(this.isNew) /*this stuff is triggered on creation properly */;
if(this.isModified) /* I want to trigger this when the parent's name changes */;
next();
});
let ParentSchema = new Schema({
name: String,
children: [ChildSchema]
});
isNew 内容按预期工作,但我想将children 的实际数组元素标记为已修改,以便在父名称更改时触发isModified 内容。我不知道该怎么做。
我试过了:
ParentModel.findById(id)
.then( (parentDocument) => {
parentDocument.name = 'mommy'; //or whatever, as long as its different.
if(parentDocument.isModified('name')){
//this stuff is executed so I am detecting the name change.
parentDocument.markModified('children');//probably works but doesn't trigger isModified on the actual child elements in the array
for(let i=0; i < parentDocument.children.length; i++){
parentDocument.markModified('children.'+i);//tried this as I thought this was how you path to a specific array element, but it has no effect.
}
parentDocument.save();//this works fine, but the child elements don't have their isModified code executed in the pre 'save' middleware
}
});
所以我的问题 - 如何将子文档的特定(或所有)数组元素标记为已修改,以使其 isModified 属性为真?请注意,我的预保存中间件执行得很好,但没有一个项目有 isModified === true;
【问题讨论】:
标签: javascript node.js mongodb typescript mongoose