How to organise the Mongodb native-driver in a big project?
At the moment I use this code in every "model" which is basically just an object in a module.
users.js
var mongo = require('mongodb');
var Users = {};
Users.db = new mongo.Db(...);
Users.db.open = function(e, c){
if(e){ throw new Error(e); } else {
console.log('connection opened'); }
};
Users.c = Users.db.collection('users');
Users.login = function(username, rawPassword, callback){
Users.c.findOne({ username: username }, function(e, o){
if(o.password === encrypt(rawPassword)){ callback(o); }
else { callback(null); }
});
};
But would this be the best way to open a database connection in each separated model? How to do proper sharing of the connection between the models? Would this be a good solution:
database-connections.js
var mongo = require('mongodb');
var RedisClient = require('redis-client');
module.exports = {
main: new mongo.Db(...),
log: new mongo.Db(...),
cache: new RedisClient(...)
};
so each time we use a database connection we can use this instead:
users.js
var mainDb = require('database-connections.js').main;
var logDb = require('database-connections.js').log;
var cacheDb = require('database-connections.js').cache;
mainDb.open(function(e, c)){
if(e){ throw new Error(e); } else {
mainDb.collection('users', function(e, c){
// do work.
});
}
});
In my answer to your previous question I said that mongodb-native api was clunky and hard to use. I think we can see here why.
Using mongojs
users.js
var db = require("mongojs").connect('maindb', ['users']);
db.users.find({},
function(err, results){
//do something with the results
})
I think this much simple and will work much better for larger applications.