creating Javascript functions in a MongoDB database

Although it’s not recommended to store your application logic in MongoDB, it’s sometimes useful to create Javascript functions for database management purposes in the database.

The process is really easy. MongoDB has a special collection named system.js, that can contain Javascript functions. Creating a function in MongoDB is as simple as inserting a record with the name and the function code into the fields named _id and value in this collection.

Example:

db.system.js.save(
  {
    _id : "myFirstFunction" ,
    value : function (a, b){ return a + b; }
  }
);

The function is now accessible in any Javascript context (for instance in a $where). If you need to access the functions from the MongoDB shell, call the command db.loadServerScripts() to load them for the current database.

 

Laat een reactie achter

Het e-mailadres wordt niet gepubliceerd.

Deze site gebruikt Akismet om spam te verminderen. Bekijk hoe je reactie-gegevens worden verwerkt.

By using this site you acknowledge the use of cookies (which are mostly harmless, btw) More information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below you are agreeing to these settings.

Close