【问题标题】:How do I mark a specific element of a subdocument array as modified in mongoose?如何在猫鼬中将子文档数组的特定元素标记为已修改?
【发布时间】: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


    【解决方案1】:

    原来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 错误,但我的问题已解决。

    【讨论】:

      猜你喜欢
      • 2018-05-27
      • 2020-06-10
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 2020-07-10
      • 2014-10-30
      • 2017-12-03
      相关资源
      最近更新 更多