Astagron
Astagron

Reputation: 277

Best practice to validate Mongoose Schema and display custom error message

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?

Upvotes: 10

Views: 6118

Answers (2)

uzai sindiko
uzai sindiko

Reputation: 649

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)

Upvotes: 5

Mika Sundland
Mika Sundland

Reputation: 18979

The easieast way to deal with error messages for the unique constraint in mongoose is to use a plugin such as mongoose-beautiful-unique-validation. It makes the error messages look like ordinary validation error messages.

Upvotes: 0

Related Questions