Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why mongoose findById return an error if ID is not found

Making an API with Node/Express + Mongo.

I'm writing some unit test and I observed if I try to get /profile/1 for _id=1 (I let mongo put the ID by default so I cannot have _id=1) i got this error

MongooseError: Cast to ObjectId failed for value "1" at path "_id"

I thought I will have an empty object User.

function getProfile(req, res) {
  const userId = req.params.userId

  User.findById(userId, "-password", (err, user) => {
    if (err) {
      console.log(err);
      res.status(400)
      res.json({
        success: false,
        err
      })
      res.end()
      return
    }

    if (!user) {
      res.status(404)
      res.json({
        success: false,
        message: `Cannot find an User with the userId: ${userId}`
      })
      res.end()
      return
    }

    res.json({
      success: true,
      user: user
    })
    res.end()
    return
  })
}

My test :

describe('Test /profile route', () => {

    it('shouldn\'t find Joe Doe\'s profile with a wrong ID\n', (done) => {
      chai.request(server)
      .get(`/profile/1`)
      .end((err, res) => {
        expect(res).to.have.status(404)
        done()
      })
    })

I thought I would have an error 404 (second if, and I know it's not the right code error, just a quick way for me to see where my test goes) but I got a 400 -> meaning an error is return.

I read mongoose documentation and I don't really see ho they explain the return value with the different methods.

like image 817
Ragnar Avatar asked Feb 17 '17 21:02

Ragnar


1 Answers

The problem is that '1' is not a valid mongoose object id. Therefore it is trying to compare different types.

Try casting it to a object id like so:

userId = mongoose.Types.ObjectId(userId)

and then run your query

User.findById(userId, "-password", (err, user) => { .... });
like image 160
MarkB Avatar answered Oct 30 '22 19:10

MarkB