Is there a feature where I can require the existing cursor in the npm mongodb library?

Postgres node driver has it to where I can grab the db cursor in any where in my node app with:

const pool = require('../../db/postgres/init').pool.

With the DB cursor that is created from with MongoClient.connect().then((db) => {}), does the mongodb npm library have a similar feature where I can grab the already created/pre-existing db curser from anywhere in my app?

Hi @Darin_Hensley, welcome to the community.

By “grabbing the cursor”, I believe you’re talking about getting a connection from a connection pool. Is this correct?

If yes, then MongoClient was designed to create and manage a connection pool for you. Note that in MongoClient.connect() you can specify a poolSize parameter (default is 5).

Thus the optimal pattern of MongoClient usage is to instantiate the MongoClient connection once for the duration of the app’s lifetime, instead of calling MongoClient.connect() for every database operation. To achieve this, you can use a global variable, for example:

var db = null // global variable to hold the connection

MongoClient.connect('mongodb://localhost:27017/', function(err, client) {
    if(err) { console.error(err) }
    db = client.db('test') // once connected, assign the connection to the global variable
})

app.get('/', function(req, res) {
    db.collection('test').find({}).toArray(function(err, docs) {
        if(err) { console.error(err) }
        res.send(JSON.stringify(docs))
    })
})

However, it is a bit different from the Postgres pool example you posted. To emulate it, you may be able to package the MongoClient connection in a separate module and ensure that it acts like a singleton in node, which is an entirely separate discussion :slight_smile:

Best regards,
Kevin

1 Like