How can I export a mongo database handler in Node.js?

2,588 views
Skip to first unread message

Muhammad Saqib

unread,
Oct 1, 2015, 12:09:04 AM10/1/15
to mongodb-user
I am new to Node and Mongo, I was trying to connect to a mongo database in one file and export the database handler to many other files, so that I need not to connect to the database in all files which need a connection to it. Here is how I attempted to do it

// db.js
var client = require('mongodb').MongoClient
var assert = require('assert')
var url = 'mongodb://localhost:27017/test'

client
.connect(url, (err, db) => {
 
assert.equal(err, null)
 
module.exports = db
})

After exporting the db handler, I tried to access methods on it in another file as follows

var db = require('./db')
console
.log(db.collection('col'))

but it throws a TypeError, saying that db.collection is not a function. How can I access the methods on db handler in other files?


Wan Bachtiar

unread,
Oct 6, 2015, 8:45:53 PM10/6/15
to mongodb-user

Hi Muhammad,

Since NodeJS leverages asynchronous calls for operations, you would want to access the collection as part of the connection callback.

For example in your file called db.js, you can export the function that establishes connection to MongoDB :

var mclient = require('mongodb').MongoClient;
var dburl = 'mongodb://localhost:27017/test';

module.exports.connect = function connect(callback) {
    mclient.connect(dburl, function(err, conn){
        /* exports the connection */
        module.exports.db = conn;
        callback(err);
    });
};


You can then utilise the exported connect function in other javascript files

example.js

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

mongo.connect(function(err){
    /* Handle any connection error here */
    if (err) throw err;

    /* Print documents in collection named 'col' */
    mongo.db.collection('col').find({}).each(function (err, doc){
        if (doc != null){
            console.log(doc);
        }
    });
});


The examples above are written in


Regards,

Wan


Reply all
Reply to author
Forward
0 new messages