MongoDB Stored Javascript from Node.JS

Node.JS from Javascript Stored MongoDB

This is just a simple example of creating and using Stored Javascripts in MongoDB and calling it from Node.js.

1. Already there

You should have installed mongodb, node.js and it also should running.

Add in your MongoDB 2 Datasets with a column ertrag as Int.

 

2. Create Node.js app

In your node.js app.js create following:

var Db = require('mongodb').Db;
var Server = require('mongodb').Server;

var db = new Db('test', new Server('127.0.0.1', 27017, {}));

db.open(function (err, pClient) {
    db.eval("gesamtertrag()", function (error, result) {
        console.log(result);

        db.close();
    });
});


3. Create Stored Javascript

in MongoVue create a new Stored Javascript with name "gesamtertrag" with following code:

function () {
	var a = 0;
	db.test_insert.find().forEach(
	 function(data) {
	 	a += data.ertrag;
	  	//print(student.name + "<p>"); 
	 } );
	 return a;
}

if you now start the app.js you will see the result.



Comments are closed