Mongoose - 默认值定义中的依赖

Mongoose - dependency in default value definition

我有简单的 Mongoose 模型:

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

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

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

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

ExampleSchema.pre('save', function(next) {
    this.partHeight = this.fullHeight / 2;
    next();
});
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);