alkhatim
alkhatim

Reputation: 363

How to reference another property in your mongoose schema

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

Upvotes: 4

Views: 1854

Answers (2)

Rohit Kashyap
Rohit Kashyap

Reputation: 1592

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;
        }
    ]
},

Upvotes: 2

libik
libik

Reputation: 23029

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

Upvotes: 0

Related Questions