Reputation: 10715
I'm setting up a Mongo script to take variables by --eval, like so:
mongo mydb myscript.js --eval "parameter = 'value'"
However, I want the script to still work without requiring the --eval
.
If this were browser-based JS, I'd just do a var internalParameter = window.parameter || null
sort of thing to get around the ReferenceError thrown by checking for an undefined variable, but mongo
doesn't have window
. Is it possible to access variables through the global object in Mongo scripting, or do I just have to wrap this in a try/catch?
Upvotes: 2
Views: 5415
Reputation: 5336
I did the following to solve a similar problem:
function set_param(name, default_val)
{
if (typeof this[name] === "undefined")
this[name] = default_val;
}
set_param("DAYS_BACK", 180);
set_param("BATCH_SIZE", 1000);
Now if either of the parameters is given with an --eval
argument, MongoDB shell will use what was provided. Otherwise it will use the default supplied by the second argument to set_param()
. The variables whose names were given as the first argument to set_param()
are safe to use once set_param()
is executed regardless of the use of --eval
.
Upvotes: 0
Reputation: 10715
Now that I've learned a little more about common JavaScript idioms, I know you can also do:
var internalParameter = typeof parameter == "undefined" ? null : parameter
Upvotes: 5
Reputation: 312035
In myscript.js you can do:
var parameter = parameter || null;
If parameter
is passed in via the --eval
it will have that value, otherwise it will be null
.
UPDATE
To do it without defining the input variable you can use the fact that this
refers to the global object in the shell and do:
var internalParameter = this.parameter || null;
Upvotes: 1
Reputation: 5539
Yes. Your script could set a default like this:
var parameter = parameter || 'default';
print('parameter = ' + parameter);
And then it would be possible to pass parameters or leave the default:
% mongo script.js
MongoDB shell version: 2.0.7
connecting to: localhost:27017/test
parameter = default
% mongo script.js --eval "var parameter = 'something else';"
MongoDB shell version: 2.0.7
connecting to: localhost:27017/test
parameter = something else
Upvotes: 0