Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a stored function from mongodb-native/node.js

I'm trying to execute a stored function from mongodb-native/node.js environment.

I have several functions inside db.system.js.

It seems Db.executeCommand() is the function but I have no idea how can I pass the function name and the arguments.

I tried db.eval() as suggested but I got the following.

> db.eval('getValue()', {}, function(er,doc) {console.log(er);console.log(doc);});
{ stack: [Getter/Setter], arguments: [ 'send', undefined ], type: 'non_object_property_call', message: [Getter/Setter] }
null

getValue is a simple function that returns an integer.

Anyone has an idea? Thanks.

like image 454
MinJae Hwang Avatar asked Feb 23 '26 08:02

MinJae Hwang


2 Answers

Assuming db is your open database handler:

db.eval("myFunction(param, param_n)", function(error, result) { });

Looks like you can pass the parameters in separately, too. https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/db.js

like image 162
cjohn Avatar answered Feb 25 '26 20:02

cjohn


There you go:

function testDB(req,res) {
        MongoClient.connect(url, function(err, db) {
            if (err) {
                console.log(err);
                res.send('connection failed');
            } else {
               db.eval("testFunction()", function(err, output) {
                    if(err){
                        console.log("ERROR: "+err);
                        res.send(err);
                        return;
                    }else{
                        res.send(output);
                        return; 
                    }
                });
                db.close();
            }
        });
    }

I am assuming that you call it for a rest API. You can change the function params based on your need. Also I assume your URL has enough permissions to call the function. If not, use a mongo tool like RoboMongo and change the permission to the user.

like image 27
Gautam Avatar answered Feb 25 '26 21:02

Gautam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!