MongoDB | Node.js Connection Pooling w/ module.exports -
hey guys i'm pretty new creating modules, i'm having bit of trouble accessing mongodb connection pool main application.
here's module:
// mongo-pool.js // ------------- var assert = require('assert'); var mongodb = require('mongodb'); var mongoclient = mongodb.mongoclient; var url = 'connection_url'; var mongopool = { start: function() { mongoclient.connect(url, function(err, db) { assert.equal(null, err); console.log("successfully connected mongo"); // make db object accessible here? }); } } module.exports = mongopool;
when require mongo-pool.js
, call mongopool.start()
says connected mongo, although db object not accessible make queries. here main js file:
var mongopool = require('./mongo-pool.js'); var pool = mongopool.start(); var collection = pool.db.collection('accounts'); collection.update( { _id: 'diynaiis' }, { $push: { children: 'julian' } } )
the variable pool undefined. can't seem figure out why, i've tried return db
in module, didn't seem work.
any appreciated, thank you!
a buddy of mine helped me figure out problem was, here's solution incase runs it.
i updated mongo-pool.js
module , assigned db property itself:
var assert = require('assert'); var mongodb = require('mongodb'); var mongoclient = mongodb.mongoclient; var url = 'my_database_url'; var mongopool = { start: function() { mongoclient.connect(url, function(err, db) { assert.equal(null, err); var self = this; self.db = db; // these assignments console.log("successfully connected mongo"); // make db object accessible here? }); } } module.exports = mongopool;
then in main.js
file:
var mongopool = require('./mongo-pool.js'); // include mongo global module new mongopool.start(); // initialize new mongodb object globally settimeout(function() { console.log(db); }, 3000); // set 3 second timeout before testing db object... // return undefined if it's called before mongo connection made
now db
object globally available module.