javascript - Mongoose:E11000 重复键改变返回消息的类型以防出错
问题描述
以下消息返回给我:E11000 duplicate key error collection ...
,当指定为 的属性之一时,unique: true
可以使用自定义的来修改此错误消息,例如:
{error: '11000', field: 'name of the field giving the problem'}
解决方案
唯一性mongoose
不是validation
参数,因此您无法为这些字段创建自定义错误消息,只能uniqueness index
在数据库中创建。
你可以做的是,在 Mongoose 中创建一个错误处理中间件,并拦截11000
错误,并custom error message
在response
.
来自猫鼬文档
// 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 重复密钥错误,但它不会告诉您是哪个字段导致了您的问题。
推荐阅读
- python - 用一组字符串重新索引熊猫系列正在删除系列中的原始数据
- python - “NoneType”对象在 BeautifulSoup 中没有属性“文本”
- azure - Azure AD Connect - 更改 sourceanchor
- python-3.x - request.args 中的烧瓶可选参数
- c# - 如何使 sql 选择动态字符串比较起作用?
- ios - 在 TabBarController 之间共享 UIViewController 实例
- python - 未找到带有参数 '('',)' 的 'user' 的反向操作。尝试了 1 种模式:['project/users/(?P
[0-9]+)/$'] - javascript - 您好我想仅通过过滤器功能过滤嵌套数组中的数据
- java - 如何在 Java 中实现多对多关系?
- node.js - React 编译错误“尝试导入错误:'./registerServiceWorker' 不包含默认导出(导入为'registerServiceWorker')。”