Mongoose.js永远不会通过集合保存字段

时间:2012-10-17 22:22:50

标签: javascript node.js mongoose

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

我有一个猫鼬模式:

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();
}

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:0)

不是直接的,但如果你刚刚修改了字段,那该怎么样:

schema.pre( 'save', function( next ) {
    if ( this.field && ( this.isModified( 'field' ) || this.isModified( 'fieldGenerated' ) ) {
        this.fieldGenerated = this.field.split( ' ' );
    }
    next();
}