首页 > 解决方案 > Mongoose:E11000 重复键改变返回消息的类型以防出错

问题描述

以下消息返回给我:E11000 duplicate key error collection ...,当指定为 的属性之一时,unique: true可以使用自定义的来修改此错误消息,例如:

{error: '11000', field: 'name of the field giving the problem'}

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


唯一性mongoose不是validation参数,因此您无法为这些字段创建自定义错误消息,只能uniqueness index在数据库中创建。

你可以做的是,在 Mongoose 中创建一个错误处理中间件,并拦截11000错误,并custom error messageresponse.

来自猫鼬文档

// Handler **must** take 3 parameters: the error that occurred, the document
// in question, and the `next()` function
schema.post('save', function(error, doc, next) {
  if (error.name === 'MongoError' && error.code === 11000) {
    next(new Error('There was a duplicate key error'));
  } else {
    next();
  }
});

注意:这允许您捕获 11000 重复密钥错误,但它不会告诉您是哪个字段导致了您的问题。


推荐阅读