Custom Error Messages with Mongoose

前端 未结 8 481
旧巷少年郎
旧巷少年郎 2021-02-01 04:06

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: {         


        
相关标签:
8条回答
  • 2021-02-01 04:46

    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' });
    
    0 讨论(0)
  • 2021-02-01 04:47

    Updated version for Mongoose 5.x.x

    MySchema.post('save', function (error, doc, next) {
        if (err.name === 'BulkWriteError' && error.code === 11000) 
            next(new Error('This item already exists, please try again'));
        else next(error);
    });
    
    0 讨论(0)
  • 2021-02-01 04:50
    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');
        }
      });
    
    0 讨论(0)
  • 2021-02-01 04:53

    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)

    0 讨论(0)
  • 2021-02-01 04:53

    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.

    0 讨论(0)
  • 2021-02-01 05:00

    Just apply a middleware.

    recordingSchema.post('save', function (error, _, next) {
        next( error.code === 11000 
          ?   new Error('This item field already exist')
          :   error)
    });
    
    0 讨论(0)
提交回复
热议问题