3

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.

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

could you give me an example? i am still having a problem with db.eval()
@MinJaeHwang: If I use something like db.system.js.save({_id:"addNumbers", value:function(x, y){ return x + y; }}); to get the stored procedure addNumbers into my database from the js command line, the node.js command: db.eval("addNumbers(4, 5)", function(error, result) { console.log(result); }); will output 9 to the console. Does that help?
It just returns null. db.eval('addNumbers(4,5)'); at mongo shell returns 9, though.
2

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.

Comments

0

It's because you are thinking it will return value , This is asynchronous call , you must pass a callback function with (err,doc) to get the return value

db.eval('addNumbers(4,5)',function(er,doc){
   console.log(doc);
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.