I have searched a lot but still wasn't able to find a specific ans. I am trying to do following:
In mongo.js
var client = require('mongodb').MongoClient,
mongodb=null;
module.exports = {
connect: function(dburl, callback) {
client.connect(dburl,
function(err, db){
mongodb = db;
if(callback) { callback(); }
});
},
db: function() {
return mongodb;
},
close: function() {
mongodb.close();
}
};
In server.js
mongodb = require('./mongo');
mongodb.connect('mongodb://localhost:27017/mydb', function() {
console.log('Connected to MongoDB.');
});
In randomfile.js
mongodb = require('./mongo');
mongodb.db()
.collection('mycollection')
.find({someField: 'myquery'}, {}, options)
.toArray(function(err, coll) {
if (err) { throw err; }
console.log(coll);
});
When I run server.js a connection is formed but when I run randomfile.js I am not able to get the connection. I encounter following error.
TypeError: Cannot read property 'collection' of undefined
Am I doing something wrong?
mongo.connectand pass it the address in randomfile.js? I don't see how you expect to get a reference to your database in randomfile.js.