Home > other >  MongoDB Connection: Timeout error with Pending Promise
MongoDB Connection: Timeout error with Pending Promise

Time:06-19

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

CodePudding user response:

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"
  • Related