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?
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.
Along with built-in validators, mongoose also provides the option of creating custom validations. Creating custom validations is also very simple.
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.
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.
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;
}
]
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With