[英]MongoDB Connection: Timeout error with Pending Promise
我正在嘗試運行nodemon server
,但出現超時錯誤, [nodemon] app crashed - waiting for file changes before starting...
我有 3 個文件,路徑如下: ./server.js
、 ./index.js
和./api/restaurants.route.js
。
服務器.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}`);
});
});
餐廳.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(...
並在控制台記錄它,以查看它輸出的內容。它輸出Promise { <pending> }
.then
和.catch
。 這並沒有改變輸出您應該嘗試在 mongodb 集群中將您的 IP 地址列入白名單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.