MongoDB连接:超时错误与未决承诺

发布于 2025-02-08 09:24:31 字数 3277 浏览 0 评论 0原文

问题摘要

我正在尝试运行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 as const a = MongoClient.connect(... and console logging it, to see what it outputs. It outputs Promise { <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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜无邪 2025-02-15 09:24:32

您应该尝试在MongoDB群集中使用白色IP地址。

  1. 转到您的MongoDB Atlas项目页面
  2. 单击“网络访问”单击
  3. “添加当前IP地址”按钮
  4. 单击“确认”

You should try whitelisting your IP address in your mongodb cluster.

  1. Go to your MongoDB Atlas Project page
  2. Click "Network Access" Click
  3. "ADD CURRENT IP ADDRESS" button
  4. Click "Confirm"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文