2016-03-05 69 views
0

我有用戶的集合:貓鼬findbyId內部服務器錯誤

db.users.find() 

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

請注意,最後一個沒有OBJECT_ID,只是我的測試。 我使用Koa2並使用異步/等待,但我認爲它不會影響。 我的路線是安裝在/API /用戶,是這樣的:

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.body = err更改ctx.throw(500),我總是在瀏覽器中獲得{}。也許這就是原因,錯誤是空的。但爲什麼?

回答

0

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

將拋出一個異常,它會通過你的try/catch語句被抓!

} catch (err) { if (err === 404 || err.name === 'CastError') { ctx.throw(404) } ctx.throw(500) } 但犯錯= 404所以將跳過if語句中的try/catch,而是做ctx.throw(500)

解決它,你可以做以下操作:

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