1

Configuration file(conf.json):

{
    "mongodb": {
        "host": "127.0.0.1",
        "port": "3000",
        "db": "myproject"
    }
} 

usage in .js file

var conf = require('./conf.json')
var host = conf.mongodb.host; 
var port = conf.mongodb.port; 
var db = conf.mongodb.db;
var url = "mongodb://"+host+":"+port+"/"+db;

After this I'm establising connection to the mongodb using the url variable.

What I want to achieve is before trying to connect to mongodb it should validate all the variables that are being set from the conf.json file. If they are undefined or something, the control shoud go back and not try and attempt the following code.

Note: I've thought of putting a check for undefined on this variables using an if condition. But I'm looking for better solution.

I've heard "||" operator of javascript can help, not sure how though?

riser101
  • 610
  • 6
  • 23

1 Answers1

0

The "||" operator can help you define standards, e.g. like so:

var host = conf.mongodb.host || "127.0.0.1";

This means that "host" gets assigned the value from "conf" if it is non-falsy, else the standard value "127.0.0.1".

Caveat: If you defined "conf.mongodb.host" to be a falsy value, like e.g. 0, the default will be applied! Have a look at Falsy values in JS.

Depending on the behavior you prefer, you might want to throw exceptions instead or implement advanced checks to make sure that e.g. "host" is actually a valid IP address.

If you absolutely want to throw an Error with the "||" operator, try:

function throwErr(msg){
    throw new Error(msg);
}

var host = conf.mongodb.host || throwErr("Mongo host undefined");
var port = conf.mongodb.port || throwErr("Mongo port undefined"); 
var db = conf.mongodb.db || throwErr("Mongo database name undefined");
Community
  • 1
  • 1
Florian
  • 712
  • 5
  • 18
  • I would prefer throwing an exception, any guidance how that could be achieved with "||" operator? – riser101 Nov 26 '15 at 09:09
  • I don't think that's possible with the "||" operator. It only works with expressions, not with statements. And you would need a statement to throw an error. – Florian Nov 26 '15 at 12:18
  • I have added another approach, but it is debatable if it is better than using if... – Florian Nov 26 '15 at 12:22