2015-02-06 4 views
0

에 의존성이 나는 간단한 몽구스 모델이 있습니다몽구스 - 기본값 정의

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

답변

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); 
을 절약 할 수 있습니다 : 원하는 구문의 예는 여기