【问题标题】:mongoose findbyId internal server error猫鼬 findbyId 内部服务器错误
【发布时间】:2016-06-19 07:21:53
【问题描述】:

我有一组用户:

db.users.find()

{ "_id" : ObjectId("56d9f3435ce78127510332ea"), "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" }
{ "_id" : ObjectId("56d9f3435ce78127510332eb"), "index" : 0, "isActive" : false, "name" : "Moore", "surname" : "Vinson", "email" : "moorevinson@conferia.com", "phone" : "+1 (902) 511-2314", "address" : "433 Sullivan Street, Twilight, Maine, 4931" }
{ "_id" : ObjectId("56d9f3435ce78127510332ec"), "index" : 4, "isActive" : false, "name" : "Madge", "surname" : "Garza", "email" : "madgegarza@conferia.com", "phone" : "+1 (828) 425-3938", "address" : "256 Bowery Street, Chesapeake, Wyoming, 1688" }
{ "_id" : "56bc57c4ea0ba50642eb0418", "index" : 10, "isActive" : true, "name" : "Maritza", "surname" : "Foster", "email" : "maritzafoster@conferia.com", "phone" : "+1 (884) 416-2351", "address" : "556 Conway Street, Ernstville, Pennsylvania, 134" }

请注意最后一个没有Object_id,仅用于我的测试。 我正在使用 Koa2 并使用 async /await 虽然我认为它没有影响。 我的路由挂载在 /api/users 上,是这样的:

import User from '../models/user'
var router = require('koa-router')();
var ObjectId = require('mongoose').Types.ObjectId; 

router
  .get('/', async ctx => ctx.body = await User.find({}))
  .get('/:id', 
    async (ctx) => {
    try {
      let id = ObjectId(ctx.params.id); 
      const user = await User.findById(id)
      if (!user) {
        ctx.throw(404)
      }
      ctx.body = user
    } catch (err) {
      if (err === 404 || err.name === 'CastError') {
        ctx.throw(404)
      }
      ctx.throw(500)
    }
  })

当我加载 http://localhost:3000/api/users 时,我的所有用户都会显示出来。

当我加载http://localhost:3000/api/users/56d9f3435ce78127510332ea 时,只显示该用户。

但是....当我加载 http://localhost:3000/api/users/56bc57c4ea0ba50642eb0418 时出现内部服务器错误。

如果我加载 http://localhost:3000/api/users/whatever 我也会收到内部服务器错误

所以我的问题: findById 总是期待一个 Object_id?如果这个 Object_id 不再在集合中,它不应该返回 404 吗?

如果我使用自己的 ID 导入数据会怎样?我不能使用 findById 方法吗?即使我评论了这一行? let id = ObjectId(ctx.params.id);

我不应该收到 404 错误吗?

如果我将 ctx.throw (500) 更改为 ctx.body = err 我总是在浏览器中得到 {}。也许这就是原因,错误是空的。但为什么呢?

【问题讨论】:

标签: mongodb mongoose koa2


【解决方案1】:

if (!user) { ctx.throw(404) }

会抛出一个异常,它会被你的 try/catch 语句捕获:

} catch (err) { if (err === 404 || err.name === 'CastError') { ctx.throw(404) } ctx.throw(500) } 但是 err != 404 所以它会跳过 try/catch 中的 if 语句,而是执行 ctx.throw(500)

要修复它,您可以执行以下操作:

} catch (err) { if (err.message === 'Not Found' || err.name === 'CastError') { ctx.throw(404) } ctx.throw(500) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-04
    • 2019-02-08
    • 1970-01-01
    • 2020-11-19
    • 2017-01-05
    • 2019-09-10
    相关资源
    最近更新 更多