MongoDB连接:超时错误与未决承诺
问题摘要
我正在尝试运行Nodemon Server
,但是我会收到一个超时错误,说[Nodemon]应用程序崩溃了 - 启动之前等待文件更改...
。
问题详细信息
我有3个文件,其中包含以下路径:./ server.js
,./ index.js
和./ api/restaurants.route。 JS
。
server.js
import express from "express";
import cors from "cors";
import restaurants from "./api/restaurants.route.js";
// Create a new express application instance
const app = express();
// apply middleware
app.use(cors());
// parse request body as JSON. Our server can accept JSON data in the body of a request
app.use(express.json());
// specify some routes. This is the path that will be used to access the API
app.use("/api/v1/restaurants", restaurants);
// If someone goes to a path that doesn't exist, return a 404 error
app.use("*", (req, res) => res.status(404).json({error : "Not found"}));
// export the application instance for use in the rest of the application
export default app
index.js
import app from "./server.js"
import mongodb from "mongodb";
import dotenv from "dotenv";
// Load environment variables from .env file, where API keys and passwords are configured
dotenv.config();
// Get access to the mongo client
const MongoClient = mongodb.MongoClient;
// set port
const port = process.env.PORT || 8000;
// Connect to the database
MongoClient.connect(
// The URL of the database to connect to
process.env.RESTREVIEWS_DB_URI,
{
// The options to use when connecting to the database
maxPoolSize: 50,
wtimeoutMS: 2500,
useNewUrlParser: true,
}
)
// If the connection is not successful, throw an error
.catch(err => {
console.log(err.stack);
process.exit(1);
})
// If the connection is successful, console log a message
.then(async client => {
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
});
restaurants.route.js
import express from "express";
// create router instance
const router = express.Router();
// respond to GET requests with hello
router.route("/").get((req, res) => {
res.send("Hello from restaurants.route.js");
})
export default router;
输出
当我运行Nodemon Server 在终端上,我在终端上获得:
[nodemon] 2.0.16
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server index.js`
然后几秒钟后
MongoServerSelectionError: connection <monitor> to [redacted] closed
at Timeout._onTimeout ([redacted]/backend/node_modules/mongodb/lib/sdam/topology.js:306:38)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)
[nodemon] app crashed - waiting for file changes before starting...
我尝试了什么?
- 我尝试存储
mongoclient.connect
作为const a = mongoclient.connect(...
和控制台记录它,查看其输出。 ; repend&gt;} - 尝试评论
。
- 我 23:00这是我实际上要实施的代码。
Problem Summary
I am trying to run nodemon server
but I get a timeout error saying [nodemon] app crashed - waiting for file changes before starting...
.
Problem Details
I have 3 files, with the following paths: ./server.js
, ./index.js
, and ./api/restaurants.route.js
.
Server.js
import express from "express";
import cors from "cors";
import restaurants from "./api/restaurants.route.js";
// Create a new express application instance
const app = express();
// apply middleware
app.use(cors());
// parse request body as JSON. Our server can accept JSON data in the body of a request
app.use(express.json());
// specify some routes. This is the path that will be used to access the API
app.use("/api/v1/restaurants", restaurants);
// If someone goes to a path that doesn't exist, return a 404 error
app.use("*", (req, res) => res.status(404).json({error : "Not found"}));
// export the application instance for use in the rest of the application
export default app
index.js
import app from "./server.js"
import mongodb from "mongodb";
import dotenv from "dotenv";
// Load environment variables from .env file, where API keys and passwords are configured
dotenv.config();
// Get access to the mongo client
const MongoClient = mongodb.MongoClient;
// set port
const port = process.env.PORT || 8000;
// Connect to the database
MongoClient.connect(
// The URL of the database to connect to
process.env.RESTREVIEWS_DB_URI,
{
// The options to use when connecting to the database
maxPoolSize: 50,
wtimeoutMS: 2500,
useNewUrlParser: true,
}
)
// If the connection is not successful, throw an error
.catch(err => {
console.log(err.stack);
process.exit(1);
})
// If the connection is successful, console log a message
.then(async client => {
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
});
restaurants.route.js
import express from "express";
// create router instance
const router = express.Router();
// respond to GET requests with hello
router.route("/").get((req, res) => {
res.send("Hello from restaurants.route.js");
})
export default router;
Output
When I run nodemon server
on the terminal, I obtain on the terminal:
[nodemon] 2.0.16
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server index.js`
and then after a couple of seconds
MongoServerSelectionError: connection <monitor> to [redacted] closed
at Timeout._onTimeout ([redacted]/backend/node_modules/mongodb/lib/sdam/topology.js:306:38)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)
[nodemon] app crashed - waiting for file changes before starting...
What have I tried?
- I tried storing
MongoClient.connect
asconst a = MongoClient.connect(...
and console logging it, to see what it outputs. It outputsPromise { <pending> }
- I tried commenting out the
.then
and.catch
. This did not change the output - I tried following this tutorial from minute 10:00 to 23:00. This is the code I am actually trying to implement. However, the code seems the same to me and the issue persists
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该尝试在MongoDB群集中使用白色IP地址。
You should try whitelisting your IP address in your mongodb cluster.