Koa-router忽略了Mongoose的async / await并且返回404总是[关闭]

问题描述 投票:2回答:1

这是路线的代码。当我使用评论的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 } }
node.js mongoose koa koa2 koa-router
1个回答
-1
投票

可能是因为mongoose承诺被弃用,在您需要mongoose库的行之后,例如:

const mongoose = require('mongoose');

您可以添加一行

mongoose.Promise = global.Promise;

要么

mongoose.Promise = require('bluebird');

如果您在项目中使用bluebird。

© www.soinside.com 2019 - 2024. All rights reserved.