QA projects. Issue Tracker

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 -

The specific part:

let updatedRecord = await Issue.findByIdAndUpdate(id, 
        (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


    throw err;

CastError: Cast to ObjectId failed for value "123" at path "_id" for model "Issue"


    "error": "could not update",
    "_id": "123"

It seems that the response is correct, but crashes on this request.

Challenge: Issue Tracker

Link to the challenge:

Hey there,

I would imagine the error is being thrown, because a non-ObjectId is being passed to the findById... methods. That is, why not try:

const ObjectId = require('mongodb').ObjectId;

// ...stuff and routes
const idToSearchWith = ObjectId(;

Model.findByIdAndUpdate(idToSearchWith, ...);

That is off the top of my head. So, do not be surprised if that is not how to get the ObjectId function - this method was mentioned somewhere in the curriculum, and you can find docs on it.

EDIT: I forgot, now that you have that, you need to try { ... } catch { ... } the step involving the ObjectId transform, and then not try to search with it, if it fails.

Hope this helps

1 Like

Thank you, looks like this worked:

      try {
        id = mongoose.Types.ObjectId(id)
      } catch (err) {
        return res.json({ error: 'could not update', _id: id })