Tell us what’s happening:
Hi all, I have a question on mongoose and these tests:
-
When the
PUT
request sent to/api/issues/{projectname}
does not include update fields, the return value is{ error: 'no update field(s) sent', '_id': _id }
. On any other error, the return value is{ error: 'could not update', '_id': _id }
. -
You can send a
DELETE
request to/api/issues/{projectname}
with an_id
to delete an issue. If no_id
is sent, the return value is{ error: 'missing _id' }
. On success, the return value is{ result: 'successfully deleted', '_id': _id }
. On failure, the return value is{ error: 'could not delete', '_id': _id }
.
I’m passing everything else, but when I try to pass an ID that does not exist in the db (like “123”) it throws a cast error. I tried catching error types of castError, but it still throws a hard error. I searched far and wide to see how can I handle a non - existent id with findByIdAndUpdate, but I could not find anything useful. Can someone please give me a hand?
Your code so far
My code - https://repl.it/@Aigarsss/boilerplate-project-issuetracker
The specific part:
let updatedRecord = await Issue.findByIdAndUpdate(id,
update,
(err, result) => {
if (!err && result) {
return res.json({result: 'successfully updated', _id: id})
} else if (!result) {
return res.json({ error: 'could not update', _id: id })
}
});
the error I get if I try this PUT via postman:
{
"_id": "123",
"open": true
}
error:
/home/runner/boilerplate-project-issuetracker/node_modules/mocha/lib/runner.js:936
throw err;
^
CastError: Cast to ObjectId failed for value "123" at path "_id" for model "Issue"
response:
{
"error": "could not update",
"_id": "123"
}
It seems that the response is correct, but repl.it crashes on this request.
Challenge: Issue Tracker
Link to the challenge: