node.js - 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
?为什么我在本地没有收到此错误?
解决方案
找到了解决方案和我犯的愚蠢错误。Heroku 无法获取 MONGODB_URI 和 PORT 等配置变量,即使我使用 dotenv 存储了它们。我在他们的网站上添加了它们,现在它可以工作了!
推荐阅读
- python - 如何使用pyodbc将值插入用户输入的列
- azure - 支持 IPv6 和 IPv4 前端的 Azure 负载均衡器
- ios - 使用 AVFoundation 生成具有透明视频覆盖的视频文件
- c# - Ajax 调用(jquery)离开页面用户而不是保持相同
- azure - 企业机器人 msbot 克隆服务命令挂起
- aws-lambda - 如何从 Athena 表访问 IAM 用户和分配的策略
- wordpress - 如果自 2015 年以来我已经在我的网站上实施了 amp,我应该使用 Cloudflare Accelerated Mobile Links 选项吗?
- java - StringToDate 和非静态变量
- python - 如何同时使用多处理池和队列?
- django - 试图将长时间运行的任务从 django 卸载到单独的线程