Custom Error Messages with Mongoose

前端 未结 8 499
旧巷少年郎
旧巷少年郎 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: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)

提交回复
热议问题