首页 > 解决方案 > API 调用在本地工作,但在 heroku 中给出 MongooseError

问题描述

我已经花了几个小时在这上面,但我找不到我做错了什么。在本地一切正常这是我的子文档

const linkSchema = new mongoose.Schema({
  tag: String,
  name: String,
  url: String,
});

const monthSchema = new mongoose.Schema({
  monthName: String,
  links: [linkSchema],
});

模型

const Link = mongoose.model("Link", linkSchema);
const Month = mongoose.model("Month", monthSchema);

以及 HTTP 请求。对于 POST 请求,我收到了一些 UnhandledPromiseRejectionWarning。我不知道为什么我会得到这个,因为我使用 catch 块处理它

app.post(`/${year}/`, (request, response) => {
  const linkToAdd = request.body;
  console.log("This is the body", linkToAdd);
  const link = new Link({
    tag: linkToAdd.tag,
    name: linkToAdd.name,
    url: linkToAdd.url,
  });
  const monthWhereYouAdd = linkToAdd.month;
  Month.findOne({ monthName: `${monthWhereYouAdd}` })
    .then((result) => {
      const linksArray = result;
      linksArray.links.push(link);
      return linksArray.save();
    })
    .then((result) => {
      console.log(result);
      response.status(200).end();
    })
    .catch((error) => next(error));
});
app.get(`/${year}/:month`, (request, response, next) => {
  Month.find({ monthName: `${request.params.month}` })
    .then((result) => {
      if (result.length > 0) {
        response.json(result);
      } else response.status(304).end();
    })
    .catch((error) => next(error));
});

当我发出 GET 请求并检查日志时

2020-12-31T16:39:23.156866+00:00 heroku[router]: at=info method=GET path="/2020/January" host=linksforyou.herokuapp.com request_id=9db58a28-cff4-41f9-a88a-4950d1c80f13 fwd="183.83.172.109" dyno=web.1 connect=2ms service=10023ms status=500 bytes=436 protocol=https

2020-12-31T16:39:23.153796+00:00 app[web.1]: Operation `months.find()` buffering timed out after 10000ms

2020-12-31T16:39:23.156276+00:00 app[web.1]: MongooseError: Operation `months.find()` buffering timed out after 10000ms

2020-12-31T16:39:23.156278+00:00 app[web.1]:     at Timeout.<anonymous> (/app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:184:20)

2020-12-31T16:39:23.156278+00:00 app[web.1]:     at listOnTimeout (internal/timers.js:554:17)

2020-12-31T16:39:23.156279+00:00 app[web.1]:     at processTimers (internal/timers.js:497:7)

months.find()Month.findOne?为什么我在本地没有收到此错误?

标签: node.jsmongodbherokumongoose

解决方案


找到了解决方案和我犯的愚蠢错误。Heroku 无法获取 MONGODB_URI 和 PORT 等配置变量,即使我使用 dotenv 存储了它们。我在他们的网站上添加了它们,现在它可以工作了!


推荐阅读