0

I have simple Mongoose model:

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

Can I set dependency from fullHeight for partHeight parameter? Example of desired syntax is here:

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

2 Answers 2

3

No, but you can setup a pre-save middleware that does this every time you save

ExampleSchema.pre('save', function(next) {
    this.partHeight = this.fullHeight / 2;
    next();
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.