amark / mongous

Simple MongoDB driver for Node.js with jQuery like syntax.
MIT License
246 stars 30 forks source link

dot syntax, once a database is connected #31

Closed konsumer closed 10 years ago

konsumer commented 10 years ago

I would like to see the database in connection optional. I like to be able to configure/set it up once, and have future commands use the same database, like so:

var $ = require("mongous").Mongous;
var c = nconf.get('database');
$().open(c.host,c.port);
$(c.database + '.$cmd').auth(c.user,c.pass,function(reply){
    db('.people').find(1, {"fname": "Tom"}, function(reply){
        console.log(reply);
    });
});

.people in this case would equal c.database + ".people"

I can sort of do this with var shorthand, but it seems just a tad clunky:

var $ = require("mongous").Mongous;
var c = nconf.get('database'), d = c.database;
$().open(c.host,c.port);
$(d + '.$cmd').auth(c.user,c.pass,function(reply){
    db(d + '.people').find(1, {"fname": "Tom"}, function(reply){
        console.log(reply);
    });
});
amark commented 10 years ago

Sorry for such a late reply, been really busy with talks and stuff.

Here is a quick fix... let me know if this is good enough?

I didn't test the code, so of course you might need to fiddle with it, but you get the concept:

module.exports = function(callback){
    var $ = require("mongous").Mongous
    , config = require('./myConfigFileForMongoDB'); // change this to reference your config.
    $().open(config.host, config.port);
    $(config.database + '.$cmd').auth(config.user, config.pass, function(reply){
        var database = function(collection){
            return $(config.database + '.' + collection);
        }
        callback(database);
    });
};

Save as "mongousDB.js". Now that we've made a wrapper for it... then use like this, in your main application.

var database = require("./mongousDB.js");
database(function($){
    $('people').find(1, {"fname": "Tom"}, function(reply){ // Note: no need for '.' prefix!
        console.log(reply);
    });
});

See? Super elegant and simple! This is why Mongous is so awesome, because you can write really easy wrapper modules like this that make everything even super-easier!

Closing for now, but totally reply and let me know your thoughts.