Search code examples
node.jsmongodbexpressmern

MongoClient.connect is not responding


I am trying to connect my Node.js (Express) with my MongoDB atlas by following the official tutorial on their website.

Here is my conn.js code below:

const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;

let _db;

module.exports = {
  connectToServer: function (callback) {
    MongoClient.connect(
      Db,
      { useNewUrlParser: true, useUnifiedTopology: true },
      (err, db) => {
        console.log('THIS LOG IS NOT DISPLAYED')
        if (db) {
          _db = db.db("employees");
          console.log("Successfully connected to MongoDB");
        }
        return callback(err);
      }
    );
  },

  getDb: function () {
    return _db;
  },
};

Here is server.js where I am calling connectToServer() function from conn.js

const express = require("express");
const app = express();

const cors = require("cors");
require("dotenv").config({ path: "./config.env" });

const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));
const dbo = require("./db/conn");
 
app.listen(port, () => {
  // HERE IS WHERE I CALL THE FUNCTION
  dbo.connectToServer(err => {
    if (err) console.error(err);
  });
  console.log(`Server is running on port: ${port}`);
});

Note, that I am getting the "Server is running on port: 5000" message, but I am not getting the "Successfully connected to MongoDB" message and I am not getting any errors, too.

P.S. I made my MongoDB network access 0.0.0.0 so that any IP address can access it. And also if I provide the wrong username and password for my ATLAS_URI, I am getting an authentication error.


Solution

  • Connect returns promise you can use like below.

    let _db;
    const client = new MongoClient(Db, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    
    module.exports = {
      connectToServer: async (callback) => {
        await client.connect();
        console.log("Connected successfully to server");
        _db = client.db(dbName);
        console.log("Successfully connected to MongoDB");
      },
    
      getDb: function () {
        return _db;
      },
    };
    

    Note: You can change the order If you want, First connect to DB then start the server. It's completely optional depending on the use case.

    (async () => {
      try {
        await dbo.connectToServer();
        app.listen(port, async () => {
          // HERE IS WHERE I CALL THE FUNCTION
          console.log(`Server is running on port: ${port}`);
        });
      } catch (error) {
        console.log(error);
      }
    })();