I'm using mongoose 4.9.0. Whilst the code below works, I get a warning like the following:
(node:24769) DeprecationWarning: Implicit async custom validators (custom validators that take 2 arguments) are deprecated in mongoose >= 4.9.0. See http://mongoosejs.com/docs/validation.html#async-custom-validators for more info.
I suspect the error is coming from the model validators.
const mongoose = require('mongoose');
const isEmail = require('validator/lib/isEmail');
const Schema = mongoose.Schema;
const userSchema = new Schema({
email: {
type: String,
unique: true,
required: true,
validate: [{ validator: isEmail, msg: 'Invalid email.' }],
},
});
module.exports = mongoose.model('User', userSchema);
The only custom validator I seem to have is isEmail
from the validator
library, which given an string value returns whether it is valid or not.
There's a sneaky mistake in your custom validator.
isEmail
function from the validator
library takes 2 parameters, even though the second one is completely optional.
isEmail(str [, options])
You can prevent mongoose from seeing it by creating a function on top of it:
validate: [{ validator: value => isEmail(value), msg: 'Invalid email.' }]
Based on the mongoose Documentation you can remove the warning by setting the isAsync attribute of the validator to false. Mongoose assumes that all functions that take in two parameters are asynchronous
validate: [{ isAsync:false, validator: isEmail, msg: 'Invalid email.' }]
http://mongoosejs.com/docs/validation.html#async-custom-validators
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