这是路线的代码。当我使用评论的Promise
时,它在体内返回123。但是使用mongoose查询它会返回404状态。日志中的项目很好。但似乎路由器只是忽略等待并立即返回404。我究竟做错了什么?
router.get('/:id', async (ctx, next) => {
// var item = await Promise.resolve(123); // this line works good!
var item = await Model.findById(ctx.params.id); // but this not
ctx.body = item;
console.log('hmm', item, ctx.response);
});
在console.log输出一切都很好,但抛出404 Not Found
像默认koa响应:
hmm { _id: 5accda0700c0afd3ca50bc67,
name: 'yuki 2',
server: 5accd5848ae2e2d2be1760c6,
owner: 5accd023cc3a90d1f73d4afd,
createdAt: 2018-04-10T15:36:39.965Z,
updatedAt: 2018-04-10T15:36:39.965Z,
__v: 0 }
{ status: 404,
message: 'Not Found',
header:
{ 'access-control-allow-credentials': 'true',
'content-type': 'text/plain; charset=utf-8',
'content-length': '9' },
body: { _id: 5accda0700c0afd3ca50bc67,
name: 'yuki 2',
server: 5accd5848ae2e2d2be1760c6,
owner: 5accd023cc3a90d1f73d4afd,
createdAt: 2018-04-10T15:36:39.965Z,
updatedAt: 2018-04-10T15:36:39.965Z,
__v: 0 } }
可能是因为mongoose承诺被弃用,在您需要mongoose库的行之后,例如:
const mongoose = require('mongoose');
您可以添加一行
mongoose.Promise = global.Promise;
要么
mongoose.Promise = require('bluebird');
如果您在项目中使用bluebird。