If you can reuse the url
variable, Andy's is a great option. If it's a one shot, as calls like this often are, I'd probably do something like this...
/*jslint sloppy:true, white:true, browser: true, maxlen:80 */
/*global MongoClient */
var dbErrHand, db;
dbErrHand = function(err, database) {
if(err) {
throw err;
}
db = database; // Killing me with the global spaghetti! ;^)
};
MongoClient.connect(
'mongodb://localhost:27017/sampleDatabase',
dbErrHand
);
That way, your code is more expressive and you know what db you're connecting to, though Andy just needs to change var url
to var mongoSampleDb
or similar to get the same advantage.
I like to pull the functions out so you can visually understand that they're reasonably discrete pieces of logic, even though I realize it isn't over 80 chars here if you put it on its own lines in the connect
call. Would think that code is a candidate for reuse in your app as well.
It's also a good general habit to pull out functions so you don't accidentally make a function inside of a loop.[1]
And, of course, there's a chance that you still end up with insanely long strings, and have to do something like...
MongoClient.connect(
'mongodb://whoLetFredNameThisServerBecauseItsTooLong.FredsCompany.com:27017'
+ '/sampleDatabase',
dbErrHand
);
Good whitespace in nested code exacerbates the problem even more, which might +1 to Andy's idea of setting up variables like this outside of any loops/ifs/nested code. At some point, it might be worth turning maxlen
off.
But bracket handling is one of the most subjective decisions there is, especially in JavaScript, where there's no sniff of a great, a priori answer. Some bristle like crazy at my parameter-per-line code, or would prefer the (
was on its own line, like this...
MongoClient.connect
(
'mongodb://localhost:27017/sampleDatabase',
dbErrHand
);
Surprisingly, JSLint still allows you plenty of room for self-expression! ;^)
[1] Nepotistic question link alert, though it was the first one I googled up. Probably an example of Google biasing my results for, um, me.