dule
dule

Reputation: 18168

Test existence of argument in mongo script

I'm trying to pass a param into a mongodb script by doing the following:

mongo --eval="foo='hello world'" test.js

But I want the variable foo to be optional (i.e., use foo if it exists, otherwise continue without it), so in test.js I test existence of the variable:

if (foo)
    print(foo)
    //do stuff with foo

This throws an error if I don't specify foo on the command-line:

$ mongo test.js
ReferenceError: foo is not defined test.js:1
failed to load: test.js

This typically works in normal JS, how do I do this in a script meant for mongo?

Basically, I want to be able to still do mongo test.js without setting the foo variable and have the script still work.

Upvotes: 0

Views: 409

Answers (1)

Bubbles
Bubbles

Reputation: 3815

I believe that mongo's js runtime is similar to node.js in that it does not allow direct access to variables that have not been defined. The way I'd test for this is to use "global.foo" (or "this.foo", depending on the situation), which will return foo if it is defined, but otherwise will be undefined (and not cause an error).

Upvotes: 5

Related Questions