![](/img/trans.png)
[英]Saving a modified document (with a modified subdocument array) in Mongoose model
[英]How do I mark a specific element of a subdocument array as modified in 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
屬性為true? 請注意,我的預保存中間件可以很好地執行,但是沒有任何項目具有isModified === true
;
事實證明,孩子本身可以使用markModified
方法(盡管由於我使用的是TypeScript,所以我對所提供的鍵入信息誤導了)。
因此,如果我這樣做:
ParentModel.findById(id)
.then( (parentDocument) => {
parentDocument.name = 'mommy'; //or whatever, as long as its different.
if(parentDocument.isModified('name')){
for(let child of parentDocument.children){
child['markModified']('name');
}
parentDocument.save();
}
});
有用。 請注意,如果我嘗試僅將子項本身標記為已修改,如下所示:
child['markModified']();
我收到錯誤:
MongoError: cannot use the part (children of children.{ name: 'theName'}) to traverse the element <bla bla bla>
我不知道為什么會這樣,但是沒關系,就我而言,將某些特定字段標記為“修改”是可以的。 很高興知道為什么會出現traverse
錯誤,但是我的問題已解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.