I have started learning Node.js and one thing which is a little bit confusing to me is Schema validation.
What would be the best practice to validate data and display custom error message to user?
Let's say we have this simple Schema:
var mongoose = require("mongoose");
// create instance of Schema
var Schema = mongoose.Schema;
// create schema
var Schema = {
"email" : { type: String, unique: true },
"password" : String,
"created_at" : Date,
"updated_at" : Date
};
// Create model if it doesn't exist.
module.exports = mongoose.model('User', Schema);
I would like to have registered users with unique emails so I've added unique: true
to my Schema. Now if I want to display error message to user which says why is he not registered, I would receive response something like this:
"code": 11000,
"index": 0,
"errmsg": "E11000 duplicate key error index: my_db.users.$email_1 dup key: { : \"[email protected]\" }",
"op": {
"password": "xxx",
"email": "[email protected]",
"_id": "56895e48c978d4a10f35666a",
"__v": 0
}
This is all a little bit messy and I would like to display to send to client side just something like this:
"status": {
"text": "Email [email protected] is already taken.",
"code": 400
}
How to accomplish this?
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const { hash } = require('../helpers/bcrypt')
const userSchema = new Schema({
email: {
type: String,
required: [true, 'email is required'],
match: [/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/, 'Invalid email format'],
validate: {
validator: function(v){
return this.model('User').findOne({ email: v }).then(user => !user)
},
message: props => `${props.value} is already used by another user`
},
},
password: {
type: String,
required: [true, 'password is required']
}
})
userSchema.pre('save', function(done){
this.password = hash(this.password)
done()
})
module.exports = mongoose.model('User', userSchema)
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