我有一個Express.js
應用程序支持MongoDB
使用Mongoose
。我需要忽略來自MongoDB的重複密鑰錯誤(錯誤代碼11000),並仍然返回204 HTTP響應。這個想法是使用save
上的post
鉤子,消耗錯誤並忽略它。貓鼬:帖子掛鉤消費錯誤
服務層
const createMyModel = (req, res, next) => {
MyModel.create({...data})
.then(createRes => res.status(204).send())
.catch(next)
}
模式 - 保存勾
MySchema.post('save', (err, res, next) => {
if (!err || (err.name === 'MongoError' && err.code === 11000)) {
// The duplicate key error is caught here but somehow
// the catch on my service layer gets triggered
next();
}else{
next(err)
}
});
很高興知道emitIndexErrors,但這並不能很好地解決我的問題。問題是在post hook中只消耗一個特定的錯誤。 –