0
我使用Koa 2和koa-router。mongoose findbyId內部錯誤
路由器文件:
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":"[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"},
....
但是如果我在瀏覽器http://localhost:3000/api/users/56bc57c48cc9e78b4ce61206
沒有任何反應執行由id來獲取,沒有錯誤。瀏覽器只是加載我以前的網頁。
如果我將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)
嘗試'get('/ api/users /:id',async(ctx,next)''localhost:3000/api/users/56bc57c48cc9e78b4ce61206' – zangw
我並不真正回答這個問題,但是您濫用mongoose和async/await。你在同步函數中使用'await'('find()','findById()')。看看Bluebird,可能[this](https://www.npmjs.com/package/mongoose-bird) – Cohars
Mongoose 4返回承諾,所以它使用異步/等待。 – user2670996