0
votes

I want to add validation with an error message for email being unique. for that I have used the plugin mongoose-unique-validator.

Here is my model

var mongoose = require('mongoose'); //V 3.6.1
var uniqueValidator = require('mongoose-unique-validator');

// User Schema
var UserSchema = mongoose.Schema({
    username: {
        type: String,
        required: true
    },
    email: {
        type: String,
        index: true, 
        unique: true,
        required: true,
        uniqueCaseInsensitive: true 
    },
    password: {
        type: String,
        required: true
    }
});

UserSchema.plugin(uniqueValidator);

If I try to save an email that is already in database, and I get ValidationError: User validation failed: email: Error, expected email to be unique. Value: [email protected] at ValidationError.inspect (C:\nodeapps\pps\node_modules\mongoose\lib\error\validation.js:57:23)

What I need is to wrap this error into ValidationError and display the error in the form when I call validate or save.

Does anyone know how to do it?

1

1 Answers

0
votes

I think you can call User.save just like this:

let user = new User({
  username: 'username',
  email: 'email',
  password: 'password'
})

user.save(function (error) {
  if (error) {
    console.log(error.message)
  }
})

Then if any error occurs while saving the user, the message field should contain the error message.