猫鼬的自定义错误消息 [英] Custom Error Messages with Mongoose

查看:72
本文介绍了猫鼬的自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,根据猫鼬 docs ,您应该能够设置自定义错误消息在模式中如下所示:

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);
    }
});

我不断得到这个:

'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?

推荐答案

自定义消息不支持唯一参数吗?

Is unique parameter not supported for custom messages?

猫鼬中的唯一性不是验证参数(例如required);它告诉Mongoose在MongoDB中为该字段创建唯一索引.

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

唯一性约束完全在MongoDB服务器中处理.当您添加具有重复密钥的文档时,MongoDB服务器将返回您显示的错误(E11000...).

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)

这篇关于猫鼬的自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆