mongoose findbyId 内部错误

mongoose findbyId Internal error

我正在使用 Koa 2 和 koa-router。

路由器文件:

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;

如果我去 url http://localhost:3000/api/users/:

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

但是如果我在浏览器中执行 get by id http://localhost:3000/api/users/56bc57c48cc9e78b4ce61206 没有任何反应,没有错误。浏览器只是加载我之前的网页。

如果我将 id 更改为一个不存在的 id,我会在浏览器中收到一个内部错误。它在终端中显示:

   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)

Mongoose 想要将有效的 ObjectId 传递给 .findById(),而 'sfggf' 不是,这就是您收到内部错误的原因。简单看一下this question.

此外,我建议使用 mongoose.Types.ObjectId.isValid() 而不是 if(/*regex is valid*/) - 但我可能错了。