I'm facing an issue with an UnhandledPromiseRejectionWarning in my code. The specific scenario involves a Mongoose Index named 'id', where I am testing the insertion of a duplicate ID that should be handled appropriately.
router.post('/create/:id', jsonParser, (req: Request, res: Response) => {
let { id } = req.params;
if (!req.body) {
return res.sendStatus(400)
}
// @TODO add validation on JSON
let promise = Requirement.create({id: id, data: req.body.data, deleted: false});
promise.then((requirement) => {
return res.json(requirement);
});
promise.catch((reason) => {
let err = {'error': reason};
return res.json(err);
});
});
The response JSON confirms that my rejection handler is being executed:
{
"error": {
"name": "MongoError",
"message": "E11000 duplicate key error collection: rex.requirements index: id_1 dup key: { : \"REQ001\" }",
"driver": true,
"index": 0,
"code": 11000,
"errmsg": "E11000 duplicate key error collection: rex.requirements index: id_1 dup key: { : \"REQ001\" }"
}
}
The warnings I am encountering are as follows:
(node:11408) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: E11000 duplicate key error collection: rex.requirements index: id_1 dup key: { : "REQ001" }
(node:11408) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.