Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Validation Based on Other Fields [duplicate]

Consider the following schema for saving time intervals in Mongoose:

let dateIntervalSchema = new mongoose.Schema({
  begin: { type: Date, required: true  },
  end: { type: Date, required: true }
})

How can I ensure that end is always greater than or equal to begin using Mongoose Validation?

like image 502
Kayvan Mazaheri Avatar asked Aug 04 '17 12:08

Kayvan Mazaheri


People also ask

What does Mongoose unique validator do?

mongoose-unique-validator is a plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.

Is Mongoose validation customizable?

Along with built-in validators, mongoose also provides the option of creating custom validations. Creating custom validations is also very simple.

How does Mongoose validation work?

If your validator function returns a promise (like an async function), mongoose will wait for that promise to settle. If the returned promise rejects, or fulfills with the value false , Mongoose will consider that a validation error.

What is the need of Mongoose .how it is useful for validation?

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB. MongoDB is a schema-less NoSQL document database.


1 Answers

I don't know if Mongoose has built-in validators for this, but something as small as the following can be used.

startdate: {
    type: Date,
    required: true,
    // default: Date.now
},
enddate: {
    type: Date,
    validate: [
        function (value) {
            return this.startdate <= value;
        }
    ]
},
like image 125
Shane Avatar answered Sep 28 '22 02:09

Shane