如何在mongoose中修改子文档数组的特定元素?

时间:2017-10-03 17:45:13

标签: javascript node.js mongodb typescript mongoose

我有一个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;

1 个答案:

答案 0 :(得分:0)

原来孩子自己可以使用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错误,但我的问题已解决。