Mongoose - 默认值定义中的依赖项

时间:2015-02-06 15:10:17

标签: node.js mongodb mongoose

我有简单的Mongoose模型:

var ExampleSchema = new mongoose.Schema({
  fullHeight: {
    type: Number
  },
  partHeight: {
    type: Number
  }
});

我可以为fullHeight参数设置partHeight的依赖关系吗?所需语法的示例如下:

var ExampleSchema = new mongoose.Schema({
  fullHeight: {
    type: Number
  },
  partHeight: {
    type: Number,
    default: fullHeight / 2
  }
});

2 个答案:

答案 0 :(得分:3)

不,但您可以设置pre-save middleware,每次保存时都会执行此操作

ExampleSchema.pre('save', function(next) {
    this.partHeight = this.fullHeight / 2;
    next();
});

答案 1 :(得分:2)

var ExampleSchema = new Schema({
    fullHeight:  { type: Number, required: true },
    partHeight:  { type: Number }
});

ExampleSchema.pre('save', function(next){
    if (!this.partHeight){
        this.partHeight = this.fullHeight / 2 ;
    }
    next();
});

mongoose.model('Example', ExampleSchema);