Member-only story
Using MongoDB with Mongoose — Model Validation
3 min readJan 19, 2021
To make MongoDB database manipulation easy, we can use the Mongoose NPM package to make working with MongoDB databases easier.
In this article, we’ll look at how to use Mongoose to manipulate our MongoDB database.
Validation
Mongoose comes with validation features for schemas.
All SchemaTypes have a built-in validator.
Numbers have min
and max
validators.
And strings have enum
, match
, minlength
, and maxlength
validators.
For example, we can write:
async function run() {
const { createConnection, Schema } = require('mongoose');
const connection = createConnection('mongodb://localhost:27017/test');
const breakfastSchema = new Schema({
eggs: {
type: Number,
min: [6, 'too few eggs'],
max: 12
},
bacon: {
type: Number,
required: [true, 'too few bacon']
},
drink: {
type: String,
enum: ['orange juice', 'apple juice'],
required() {
return this.bacon > 3;
}
}
});
const Breakfast = connection.model('Breakfast', breakfastSchema);
const badBreakfast = new Breakfast({
eggs: 2,
bacon: 0,
drink: 'Milk'
});
let error = badBreakfast.validateSync();
console.log(error);
}
run();