MongoDB PHP Driver: Using Execute for Stored JS

假如想象 提交于 2019-12-12 00:28:17

问题


I created a Stored JS function which supposedly completes a very tedious job, faster and efficiently. Now after a investing long working hours I came up with completing this functionality.

So my function is suppose myFunc();

db.system.js.save(
{
 _id : "myFunc" ,
 value : function (param1,param2,param3....){ ... }});

Once I was through with completing this function, and testing it with Mongo Shell as

db.eval("myFunc('a','b'...)");

and

db.loadServerScripts();
myFunc('a','b',..);

I was satisfied it will work, Now the problem begins, How to achieve this with PHP?

$cmd = 'db.eval("myFunc(\'a\',\'b\'...);");';
$data = $mongo_db->execute($cmd);
var_dump($data);

$data comes up with nothing..!!

array(2) { ["retval"]=> NULL ["ok"]=> float(1) } 

Somebody tell me please what the heck am I doing wrong..!!


回答1:


You have a similar question at: Calling a stored procedure via PHP in MongoDB

Anyway as mongodb docs says:

Note We do not recommend using server-side stored functions if possible.

Is a better practice execute directly the JS with MongoDB::execute instead of store it in the db.system.js and after call it:

$func = 
    "function(greeting, name) { ".
        "return greeting+', '+name+', says '+greeter;".
    "}";
$scope = array("greeter" => "Fred");

$code = new MongoCode($func, $scope);

$response = $db->execute($code, array("Goodbye", "Joe"));
echo $response['retval'];

From: http://php.net/manual/en/mongodb.execute.php

With the MongoCode object you can use scoping and create PHP objects with you JS, and you can have this JS on your PHP project at the vcs, all together.




回答2:


The Simple workaround I found:

var out = db.eval("abc(param1,param2..)"); return(JSON.stringify(out));

I know its not at all advisable way to achieve this, but till the time I find a better workaround( as Stored JS is not an advisable method ) its the only way I have. Will post in case of any failure.



来源:https://stackoverflow.com/questions/20242361/mongodb-php-driver-using-execute-for-stored-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!