Custom Error Messages with Mongoose

2020-05-25 06:52发布

So according to the mongoose docs, you are supposed to be able to set a custom error message in the schema like so:

 var breakfastSchema = new Schema({
  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  },
  bacon: {
    type: Number,
    required: [true, 'Why no bacon?']
  }
});

So I wanted to do something similar:

var emailVerificationTokenSchema = mongoose.Schema({
   email: {type: String, required: true, unique: [true, "email must be unique"]},
   token: {type: String, required: true},
   createdAt: {type: Date, required: true, default: Date.now, expires: '4h'}
});

The idea being that when you attempt to save one of these tokens, and there is already a conflicting one it'll pump out an error message that says "email must be unique".

However when I do something like this (where I save a token with the same email):

verificationToken.save( function (err) {
    if (err) {
      return console.log(err);
    }
    else {
      return console.log(err);
    }
});

I keep getting this:

'E11000 duplicate key error: index ___.emailVerificationToken.$email_1 dup key: { : "_____@wdad.com

Any thoughts? Is unique parameter not supported for custom messages? Is this a viable way of going about things?

7条回答
该账号已被封号
2楼-- · 2020-05-25 07:09

You can rewrite error messages in source, so in node modules. Here is a path for do it: YOUR_PROJECT/node_modules/mongoose/lib/error/validation.js

then you dont have problem with any additional package for that.

查看更多
戒情不戒烟
3楼-- · 2020-05-25 07:23

Is unique parameter not supported for custom messages?

Uniqueness in Mongoose is not a validation parameter (like required); it tells Mongoose to create a unique index in MongoDB for that field.

The uniqueness constraint is handled entirely in the MongoDB server. When you add a document with a duplicate key, the MongoDB server will return the error that you are showing (E11000...).

You have to handle these errors yourself if you want to create custom error messages. The Mongoose documentation ("Error Handling Middleware") provides you with an example on how to create custom error handling:

emailVerificationTokenSchema.post('save', function(error, doc, next) {
  if (error.name === 'MongoError' && error.code === 11000) {
    next(new Error('email must be unique'));
  } else {
    next(error);
  }
});

(although this doesn't provide you with the specific field for which the uniqueness constraint failed)

查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-05-25 07:24

Thanks for all answers, I've figured out my problem.

My schema is like that.

var User = new Schema({
  username: {type: String, required: [true, "Username is required"], unique: true},
  email: {type: String, required: [true, "Email is required"], unique: true},
  password: {type: String, required: true, unique: false},
});

I recommend to use like a function.

You can use like this;

User.post("save", function (error, doc, next) {

  if (error.keyValue.email != null && error.name === "MongoError" && error.code === 11000) {

    console.log("Email must be unique");
  } else if (error.keyValue.username != null && error.name === "MongoError" && error.code === 11000) {
    console.log("Username must be unique");
  } else {
    console.log("not found any idea, search for another reasons");
  }
});
查看更多
Anthone
5楼-- · 2020-05-25 07:25
verificationToken.save( function (err) {
    if (err) {
      return res.status(400).send({
          message: (err.name === 'MongoError' && err.code === 11000) ? 'Email already exists !' : errorHandler.getErrorMessage(err)
      });
    }
    else {
      return console.log('No Error');
    }
  });
查看更多
时光不老,我们不散
6楼-- · 2020-05-25 07:30

Just apply a middleware.

recordingSchema.post('save', function (error, _, next) {
    next( error.code === 11000 
      ?   new Error('This item field already exist')
      :   error)
});
查看更多
孤傲高冷的网名
7楼-- · 2020-05-25 07:33

It is not directly possible as you tried it but you may want to have a look at mongoose-unique-validator which allows for custom error message if uniqueness would be violated.

In particular the section about custom errors should be of interest to you.

To get your desired

"email must be unique"

it would look similar to this

var uniqueValidator = require('mongoose-unique-validator');
...
emailVerificationTokenSchema.plugin(uniqueValidator, { message: '{PATH} must be unique' });
查看更多
登录 后发表回答