skip to Main Content

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.

2

Answers


  1. 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);
      }
    })();
    
    Login or Signup to reply.
  2. Callback Support has been removed from v5 hence the console.log statements in callback function are not getting printed. To make it work you can use promises/async-await.
    Due to same reason an error is thrown when authentication is wrong as connect function is running but failing in this case.

    Change log for the same. => "Node.js driver v5 drops support for callbacks in favor of a Promise-only API."

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search