Databases Reference
In-Depth Information
There are downsides to using stored JavaScript: it keeps portions of your code out of
source control, and it can obfuscate JavaScript sent from the client.
The best reason for storing JavaScript is if you have multiple parts of your code (or code
in different programs or languages) using a single JavaScript function. Keeping such
functions in a central location means they do not need to be updated in multiple places
if changes are required. Stored JavaScript can also be useful if your JavaScript code is
long and executed frequently, because storing it once can cut down on network
transfer time.
Security
Executing JavaScript is one of the few times you must be careful about security with
MongoDB. If done incorrectly, server-side JavaScript is susceptible to injection attacks
similar to those that occur in a relational database. Luckily, it is very easy to prevent
these attacks and use JavaScript safely.
Suppose you want to print “Hello, username !” to the user. If the username is in a variable
called username , you could write a JavaScript function such as the following:
> func = "function() { print('Hello, "+username+"!'); }"
If username is a user-defined variable, it could contain the string "'); db.dropData
base(); print('" , which would turn the code into this:
> func = "function() { print('Hello, '); db.dropDatabase(); print('!'); }"
Now your entire database has been dropped!
To prevent this, you should use a scope to pass in the username. In PHP, for example,
this looks like this:
$func = new MongoCode("function() { print('Hello, "+username+"!'); }",
... array("username" => $username));
Now the database will harmlessly print this:
Hello, '); db.dropDatabase(); print('!
Most drivers have a special type for sending code to the database, since code can actually
be a composite of a string and a scope. A scope is just a document mapping variable
names to values. This mapping becomes a local scope for the JavaScript function being
executed.
The shell does not have a code type that includes scope; you can only
use strings or JavaScript functions with it.
 
Search WWH ::




Custom Search