mongoose findbyId Internal error

300 Views Asked by At

I'm using Koa 2 and koa-router.

The router file:

import User from '../models/user'
var router = require('koa-router')();
router
  .get('/', async ctx => ctx.body = await User.find({}))
  .get('/:id', async (ctx, next) =>
    ctx.body = await User.findById(ctx.params.id))
module.exports = router;

get results are ok if I go to the url http://localhost:3000/api/users/:

[{"_id":"56bc57c48cc9e78b4ce61206","index":3,"isActive":true,"name":"Price","surname":"Shelton","email":"[email protected]","phone":"+1 (863) 516-2166","address":"587 Classon Avenue, Grapeview, New Jersey, 7382"},{"_id":"56bc57c47bb0e8884071eb00","index":1,"isActive":false,"name":"Noble","surname":"Downs","email":"[email protected]","phone":"+1 (812) 412-3775","address":"357 River Street, Chelsea, District Of Columbia, 5938"},
....

However if I execute get by id in the browser http://localhost:3000/api/users/56bc57c48cc9e78b4ce61206 nothing happens, no error. The browser just load the webpage that I had before.

If I change the id to one id that doesn't exists, I got an Internal error in the browser. It shows in the terminal:

   CastError: Cast to ObjectId failed for value "sfggf" at path "_id"
      at MongooseError.CastError (/home/juanda/koa2-api/node_modules/mongoose/lib/error/cast.js:19:11)
      at ObjectId.cast (/home/juanda/koa2-api/node_modules/mongoose/lib/schema/objectid.js:136:13)
      at ObjectId.castForQuery (/home/juanda/koa2-api/node_modules/mongoose/lib/schema/objectid.js:176:15)
      at cast (/home/juanda/koa2-api/node_modules/mongoose/lib/cast.js:174:32)
      at Query.cast (/home/juanda/koa2-api/node_modules/mongoose/lib/query.js:2542:10)
      at Query.findOne (/home/juanda/koa2-api/node_modules/mongoose/lib/query.js:1239:10)
      at /home/juanda/koa2-api/node_modules/mongoose/lib/query.js:2143:21
      at new Promise.ES6 (/home/juanda/koa2-api/node_modules/mongoose/lib/promise.js:45:3)
      at Query.exec (/home/juanda/koa2-api/node_modules/mongoose/lib/query.js:2136:10)
      at Query.then (/home/juanda/koa2-api/node_modules/mongoose/lib/query.js:2166:15)
1

There are 1 best solutions below

0
On BEST ANSWER

Mongoose wants a valid ObjectId passed to .findById(), which 'sfggf' is not, that's why you get the internal error. Simply take a look at this question.

Plus I would recommend using mongoose.Types.ObjectId.isValid() instead of an if(/*regex is valid*/) - but I might be wrong.