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: { : \"test@test.com\" }",
"op": {
"password": "xxx",
"email": "test@test.com",
"_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 test@test.com is already taken.",
"code": 400
}
How to accomplish this?