代码之家  ›  专栏  ›  技术社区  ›  WillyC

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

  •  0
  • WillyC  · 技术社区  · 8 年前

    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 stuff按预期工作,但我想标记 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

    1 回复  |  直到 8 年前
        1
  •  0
  •   WillyC    8 年前

    结果是 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