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.
It looks like the MongoDB connect() method now returns a promise, instead of accepting a callback, thus the code should be:
I also came up with another sligthly different solution: