我有简单的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
}
});
答案 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);