I am trying to connect my mongodb server with express. But the server is not listening when i am giving the listen function inside connectToServer(). The following snippet is the index.js file.
const express = require("express");
const { connectToServer } = require("./utils/dbConnect");
const usersRoute=require('./routes/users.route.js');
const app = express();
const port = 5000;
connectToServer((err) => {
app.listen(port, () => {
console.log({ port });
}
)});
app.use('/users',usersRoute)
app.get("/", (req, res) => {
res.send("Hello World");
});
Here is the dbConnect.js snippet:
const { MongoClient } = require("mongodb");
const connectionString = "mongodb://localhost:27017";
const client = new MongoClient(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let dbConnection;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
if (err || !db) {
return callback(err);
}
dbConnection = db.db("users");
console.log("Successfully connected to MongoDB.");
return callback();
});
},
getDb: function () {
return dbConnection;
},
};
The server stucks at [nodemon] starting node index.js
I was expecting to get the server running and listening. But it doesn't.