skip to Main Content

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


  1. Chosen as BEST ANSWER

    @Sayyid Shaban I was going in the same direction :) I post here as answer what I've ended up with; something like:

    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;
    

    but your answer looks great: accepted! Thanks!


  2. 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 the MongoConnect class to use promises instead of callbacks. Here’s an updated version of the code:

    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.error('Error connecting to DB:', err);
        }
      }
    }
    
    export default MongoConnect;
    

    By using the await keyword before this.mongoClient.connect(), the execution will pause until the connection is established or an error occurs. If an error occurs, it will be caught in the catch 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.

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