4

If I have a property in my schema that depends on another one (like it's minimum value), how do define that in my schema?

I have an endDate and an actualEndDate properties in my schema, the second one will always be greater than or equal to the first one, how do I put that in my schema

const schema = new mongoose.Schema({
  endDate: {
    type: Date,
    min: new Date(),
    required: true
  },
  actualEndDate: {
    type: Date,
    min: new Date(),  // I need this to be min: this.endDate or something
  }
});
Lee Brindley
  • 6,242
  • 5
  • 41
  • 62
alkhatim
  • 353
  • 1
  • 10
  • Not being rude this seems quite unfair, I provided you with exactly what you needed and the marked answer is not quite what you wanted, I wonder why is that. – Rohit Kashyap Sep 02 '19 at 12:48
  • im sorry im new to asking questions on stackoverflow and I thought I marked both answers (because both satisfy my need) and it turns out I can only mark one and the second one did overwrite your mark ... yesyour solution is the actual one I used in my code and i'll give it back the mark .. sorry again – alkhatim Sep 04 '19 at 09:09
  • It happens, I am just starting out on StackOverflow and quickly hoping to get as many points possible, hence the comment. – Rohit Kashyap Sep 04 '19 at 09:31

2 Answers2

2

You can add your own custom validation.

Try this:

endDate: {
    type: Date,
    required: true,
    // min: new Date()
    // default: Date.now
},
actualEndDate: {
    type: Date,
    validate: [
        function (value) {
            return this.endDate <= value;
        }
    ]
},
Rohit Kashyap
  • 1,553
  • 1
  • 10
  • 16
0

before you save/update any document you can add pre-save hooks that can check the validity of document and throw error or update some value based on your logic.

https://mongoosejs.com/docs/middleware.html#pre

libik
  • 22,239
  • 9
  • 44
  • 87