2015-02-06 103 views
0

依賴我有簡單的貓鼬模型:貓鼬 - 默認值定義

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

回答

3

沒有,但你可以設置一個pre-save middleware,這確實每次保存

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