I\'m using node-mongodb-native driver with mongodb to write a website.
I have a question about how to open mongodb connection once, then use it in collection name us
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({ ...
});
Accepted answer is 3 year old and it wont work with latest node-mongodb-native driver. I have modified @moka answer and added some delay and retry logic.
var MongoClient = require('mongodb').MongoClient;
var events = require('events');
var event = new events.EventEmitter();
var database = null;
var retries = 0;
var delay = 300;
setTimeout(connect,delay);
// Use connect method to connect to the server
function connect(){
MongoClient.connect(process.env.MONGODB_URL, function(err, db) {
if(!err){
console.log("Connected successfully to server");
database = db;
event.emit('dbconnect');
} else {
if(retries < 4){
console.log('Retrying to connect db %s', retries++);
setTimeout(connect,delay);
} else {
console.log('Unable to connect db');
}
}
});
}
exports.get = function(fn) {
if(database !== null) {
fn(database);
} else {
event.on('dbconnect', function() {
fn(database);
});
}
};