Search code examples
node.jsmongodbmongodb-nodejs-driver

Store MongoClient.connect()


I work on a project whose code is divided into multiple js files. Until now, I 've been calling MongoClient.connect() multiple times (in each file using the db). That's when I got multiple deprecation warnings:

the options [servers] is not supported
the options [caseTranslate] is not supported
the options [dbName] is not supported
the options [srvHost] is not supported
the options [credentials] is not supported

I quickly found out it was related to all these open connections. Even though I can store MongoClient in a separate file, how can I store MongoClient.connect(), since a code that uses the database looks like that:

MongoClient.connect((err) => {
    // code here
});

and not like that:

MongoClient.connect()
// code here

Solution

  • EDIT: well, it seemed to work, but it looks like the exports of the file are equal to {}...


    The problem seems to be solved by putting the connection in a separate file (yes, I finally found out how to do it!).

    mongoClient.js

    require("dotenv").config();
    
    // Declaring and configuring the mongoDB client
    const { MongoClient } = require("mongodb");
    const mongo = new MongoClient(process.env.MONGO_AUTH, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    
    mongo.connect((err, result) => { // note the 'result':
    
        // result == mongo ✅
    
        // Exports the connection
        module.exports = result;
    
        // Logs out if the process is killed
        process.on("SIGINT", function () {
            mongo.close();
        });
    });
    
    

    Other file using the db

    const mongo = require("./mongoClient")
    
    const collection = mongo.db("niceDB").collection("coolCollection")
    collection.findOne({fancy: "document"}); // It works!