Member-only story
Using MongoDB with Mongoose — Async Validators and Validation Errors
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.
Async Custom Validators
We can add custom validators that are async.
For example, we can write:
async function run() {
const { createConnection, Schema } = require('mongoose');
const connection = createConnection('mongodb://localhost:27017/test');
const userSchema = new Schema({
email: {
type: String,
validate: {
validator(v) {
return Promise.resolve(/(.+)@(.+){2,}\.(.+){2,}/.test(v));
},
message: props => `${props.value} is not a email!`
},
required: [true, 'Email is required']
}
});
const User = connection.model('User', userSchema);
const user = new User();
user.email = 'test';
try {
await user.validate();
} catch (error) {
console.log(error);
}
}
run();
to add the validator
method to our method that returns a promise instead of a boolean directly.
Then we can use the validate
method to validate the values we set.