How to Properly Reuse Connection to Mongodb Across Nodejs Application and Modules

How to reuse mongodb connection in node.js

You can connect once, and then reuse it as many times as you want:

var mongodb = require('mongodb');
var events = require('events');
var event = new events.EventEmitter();
var access = new mongodb.Server(host, port, { });
var client = null;

new mongodb.Db('YOUR DATABASE', access, { safe: true, auto_reconnect: true }).open(function (err, c) {
if (!err) {
client = c;
console.log('database connected');
event.emit('connect');
} else {
console.log('database connection error', err);
event.emit('error');
}
});

exports.get = function(fn) {
if(client) {
fn(client);
} else {
event.on('connect', function() {
fn(client);
});
}
};

And then reuse it:

var db = require('./db');
var items;
db.get(function(client) {
items = new mongodb.Collection(client, 'collection');
});

// then anywhere in your code
db.get(function() {
// items.find({ ...
});

Node.js and MongoDB, reusing the DB object

You could always write a module which initializes your database connections, and makes them accessible throughout your program. For example:

mongo.js

var mongodb = require('mongodb');

module.exports.init = function (callback) {
var server = new mongodb.Server("127.0.0.1", 27017, {});
new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
//export the client and maybe some collections as a shortcut
module.exports.client = client;
module.exports.myCollection = new mongodb.Collection(client, 'myCollection');
callback(error);
});
};

app.js

var mongo = require('./mongo.js');

//setup express...

//initialize the db connection
mongo.init(function (error) {
if (error)
throw error;

app.listen(80); //database is initialized, ready to listen for connections
});

randomFile.js

var mongo = require('./mongo.js');

module.exports.doInsert = function () {
//use the collection object exported by mongo.js
mongo.myCollection.insert({test: 'obj'}, {safe:true}, function(err, objects) {
if (err)
console.warn(err.message);
});
};

I know people talk about pooling, but when I did benchmarking of pooling mongo connections vs. a single connection for all requests, the single connection actually performed better. Granted, this was about a year ago, but I doubt that basic concept has changed. All the requests are asynchronous, so it's not like multiple connections are necessary in order to make simultaneous requests.

As far as MongoClient, I guess that's the new syntax they're encouraging. Either way, it's essentially a client object that you want to keep and make accessible regardless of which style you use.

What is best way to handle global connection of Mongodb in NodeJs

Create a Connection singleton module to manage the apps database connection.

MongoClient does not provide a singleton connection pool so you don't want to call MongoClient.connect() repeatedly in your app. A singleton class to wrap the mongo client works for most apps I've seen.

const MongoClient = require('mongodb').MongoClient

class Connection {

static async open() {
if (this.db) return this.db
this.db = await MongoClient.connect(this.url, this.options)
return this.db
}

}

Connection.db = null
Connection.url = 'mongodb://127.0.0.1:27017/test_db'
Connection.options = {
bufferMaxEntries: 0,
reconnectTries: 5000,
useNewUrlParser: true,
useUnifiedTopology: true,
}

module.exports = { Connection }

Everywhere you require('./Connection'), the Connection.open() method will be available, as will the Connection.db property if it has been initialised.

const router = require('express').Router()
const { Connection } = require('../lib/Connection.js')

// This should go in the app/server setup, and waited for.
Connection.open()

router.get('/files', async (req, res) => {
try {
const files = await Connection.db.collection('files').find({})
res.json({ files })
}
catch (error) {
res.status(500).json({ error })
}
})

module.exports = router

How do I manage MongoDB connections in a Node.js web application?

The primary committer to node-mongodb-native says:

You open do MongoClient.connect once when your app boots up and reuse
the db object. It's not a singleton connection pool each .connect
creates a new connection pool.

So, to answer your question directly, reuse the db object that results from MongoClient.connect(). This gives you pooling, and will provide a noticeable speed increase as compared with opening/closing connections on each db action.

How to pass mongoDB into function in Node.js correctly

Yes, you are creating multiple DB clients. You can avoid it like this:

let client;
export default async function makeDb() {
const { MongoClient } = mongodb;
const url = process.env.DB_URL;

if (!client) {
client = new MongoClient(url,
{
useNewUrlParser: true,
useUnifiedTopology: true,
});
await client.connect();
}

const db = await client.db('myDB');
return db;
}


Related Topics



Leave a reply



Submit