// 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
})
var db = require('./db')
console.log(db.collection('col'))
db.collection is not a function. How can I access the methods on db handler in other files?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