I am trying to follow a course on MongoDB and I have problems running the following code that should allow me to connect to mongoDB. I have two modules:
mongoConnect.js
import { MongoClient} from 'mongodb';
import {EventEmitter} from 'events';
const uri = "<MYCONNSTRING>";
const dbName = "test";
class MongoConnect extends EventEmitter{
constructor(){
super();
this.mongoClient = new MongoClient(uri,{useUnifiedTopology:true});
}
connect() {
this.mongoClient.connect((err,mongodb)=>{
if(err) throw err;
console.log('Connection to DB Established');
MongoConnect.blogDatabase = mongodb.db(dbName);
this.emit('dbConnection');
})
}
};
export default MongoConnect;
App.js (main module file)
import express from 'express';
import MongoConnect from './mongoConnect.js';
const port = process.env.PORT || 3000;
const app = express();
const mongoConnect = new MongoConnect();
mongoConnect.on('dbConnection', ()=> {
app.listen(port, ()=>{
console.log(`server listening on port: ${port}`);
});
});
mongoConnect.connect();
The problem is: the callback inside the connect()
method is never executed. I don’t see messages in console and I don’t know how to proceed.
2
Answers
@Sayyid Shaban I was going in the same direction :) I post here as answer what I've ended up with; something like:
but your answer looks great: accepted! Thanks!
Based on the code you provided, it appears that you are using the MongoDB Node.js driver version 3.x or higher, which introduced changes in the connection API. The
connect
method in the new driver returns a promise instead of accepting a callback function.To fix the issue, you can modify your
connect
method in theMongoConnect
class to use promises instead of callbacks. Here’s an updated version of the code:By using the
await
keyword beforethis.mongoClient.connect()
, the execution will pause until the connection is established or an error occurs. If an error occurs, it will be caught in thecatch
block, where you can handle it accordingly.With this modification, the
dbConnection
event should be emitted once the connection is established, and the server should start listening on the specified port.Make sure to update the
mongodb
package to the latest version and ensure that your MongoDB connection string (<MYCONNSTRING>
) is valid.