MongoClient connect callback does not work

116 views Asked by At

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.

1

There are 1 answers

0
Riccardo De Contardi On

It looks like the MongoDB connect() method now returns a promise, instead of accepting a callback, thus the code should be:

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});
    }
    async connect() {
        try {
            await this.mongoClient.connect();
            console.log('Connection to DB Established');
            MongoConnect.blogDatabase = this.mongoClient.db(dbName);
            this.emit('dbConnection');
        } catch (err) {
          console.log(err);
        }          
    }
};
export default  MongoConnect;

I also came up with another sligthly different solution:

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().then(
            mongoClient=> {
                console.log('Connection to DB Established');
                MongoConnect.blogDatabase = mongoClient.db(dbName);
                this.emit('dbConnection');
            },
            err => console.log(err)
        );            
    }
};
export default  MongoConnect;