2

有没有办法在猫鼬中将字段标记为未修改?

我有一个猫鼬模式:

var schema = mongoose.Schema({
    field          : { type : String   }
  , fieldGenerated : { type : [String] }
});

我想让它fieldGenerated永远不会通过model.set( ... ).

应该设置它的唯一方法是在预保存中间件中:

schema.pre( 'save', function( next ) {

    // Any way to mark fieldGenerated as NOT modified here?

    // I only want to set fieldGenerated if field was set.
    // I don't want fieldGenerated to be set any other way.
    if ( this.field && this.isModified( 'field' ) ) {
        this.fieldGenerated = this.field.split( ' ' );
        this.markModified( 'fieldGenerated' );
    }

    next();
}

有没有办法做到这一点?

4

1 回答 1

0

不是直接的,但是如果你只是重新生成字段,如果它被修改了:

schema.pre( 'save', function( next ) {
    if ( this.field && ( this.isModified( 'field' ) || this.isModified( 'fieldGenerated' ) ) {
        this.fieldGenerated = this.field.split( ' ' );
    }
    next();
}
于 2012-10-19T15:55:46.087 回答