2017-02-09 59 views
0

我有一個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) 
    } 
}); 

回答

1

next回調Mongoose跟蹤一種叫做firstError。這是內部錯誤如重複鍵錯誤被存儲的地方。這可以防止用戶覆蓋錯誤狀態,並且下次調用總是會導致檢查firstError並觸發承諾拒絕,即使有人試圖呼叫next()next(null)

0

如果你想忽略他們完全我想你可以設置emitIndexErrors假的schema.options對象。

http://mongoosejs.com/docs/guide.html#emitIndexErrors

+0

很高興知道emitIndexErrors,但這並不能很好地解決我的問題。問題是在post hook中只消耗一個特定的錯誤。 –