开发者

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

开发者 https://www.devze.com 2023-03-31 10:05 出处:网络
I\'m trying to execute a stored function from mongodb-native/node.js environment. I have several functions inside db.system.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', undef开发者_运维百科ined ], type: 'non_object_property_call', message: [Getter/Setter] }
null

getValue is a simple function that returns an integer.

Anyone has an idea? Thanks.


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


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.


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);
})
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号