【发布时间】:2019-04-13 04:08:02
【问题描述】:
我正在使用 MERN 应用程序。在我的 express.js 模型之一中,我有独特的电子邮件架构,如下所示
email: {
type: String,
trim: true,
required: true,
minlength: 3,
unique: true
},
当我保存如下记录时,我正在检查电子邮件地址的唯一性
address.save()
.then(address => {
//other code
})
.catch(err => {
console.log(err);
res.status(500).json({
message: 'Error Occured',
error: err
});
});
我在终端中遇到错误。
{ MongoError: E11000 duplicate key error collection: addresses.addresses index: email_1 dup key: { : "nowphp@yahoo.com" }
[0] at Function.create (/home/foysal/Videos/my-app/node_modules/mongodb-core/lib/error.js:43:12)
[0] at toError (/home/foysal/Videos/my-app/node_modules/mongodb/lib/utils.js:149:22)
[0] at coll.s.topology.insert (/home/foysal/Videos/my-app/node_modules/mongodb/lib/operations/collection_ops.js:859:39)
[0] at /home/foysal/Videos/my-app/node_modules/mongodb-core/lib/connection/pool.js:532:18
[0] at process._tickCallback (internal/process/next_tick.js:61:11)
[0] driver: true,
[0] name: 'MongoError',
[0] index: 0,
[0] code: 11000,
[0] errmsg:
[0] 'E11000 duplicate key error collection: addresses.addresses index: email_1 dup key: { : "nowphp@yahoo.com" }',
[0] [Symbol(mongoErrorContextSymbol)]: {} }
我想将此错误 errmsg:
'E11000 duplicate key error collection: addresses.addresses index: email_1 dup key: { : "nowphp@yahoo.com" }', 修改为 Email already Exists 并将其传递给 React(前端)。
我该怎么做?
更新
我在express.js中使用下面的代码
address.save()
.then( address => {
// others code
})
.catch( err => {
const errString = err.toString();
if (errString.includes("E11000")) return res.status(404).json({ err: 'That email is already in use!' });
});
我的 React Redux 操作如下所示
export const addAddress = value => dispatch => {
return Axios.post('/api/address', value)
.then( response => {
// other code
})
.catch( error => {
console.log('actionError', error )
});
};
我在控制台中遇到以下错误
Error: "Request failed with status code 404"
【问题讨论】:
标签: node.js reactjs mongodb express