簡體   English   中英

如何在貓鼬中將子文檔數組的特定元素標記為已修改?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM