In my application im using node.js with mongoDB.Below is my sample code.
var mongodb = require('mongodb');
var server = new mongodb.Server("localhost", 27017, {});
new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
if (error) throw error;
var collection = new mongodb.Collection(client, 'test_collection');
collection.insert({hello: 'world'}, {safe:true},
function(err, objects) {
if(!err){
console.log('Data inserted successfully.');
}
if (err && err.message.indexOf('E11000 ') !== -1) {
// this _id was already inserted in the database
}
});
});
Now i need the mongoDB instance to other modules in my app.How can i do this.
A simple way, if we assume the code you posted is in app.js you can rewrite line 2 to:
var server = exports.db = new mongodb.Server("localhost", 27017, {});
And in the modules that needs access to the instance simply write:
require('app').db
A more common way is probably to put shared stuff in a settings.js file or to have a dedicated database interface module.
Update
To get access to the opened client you'd in the same way expose the client:
new mongodb.Db('test', server, {w: 1}).open(function (error, client) {
exports.client = client;
// ...
});