从PHP调用MongoDB中存储的JavaScript函数

时间:2010-10-14 22:27:50

标签: php mongodb java-stored-procedures mongodb-php

我将此函数存储在db.system.js

function SomeFunc(o) {
    x = db.Collection;
    while( 1 ) {
        var c = x.find({},{_id:1}).sort({_id:-1}).limit(1);
        var i = c.hasNext() ? c.next()._id + 1 : 1;
        o._id = i;
        x.insert(o);
        var err = db.getLastErrorObj();
        if( err && err.code ) {
            if( err.code == 11000 /* dup key */ )
                continue;
            else
                print("unexpected error inserting data: " + tojson(err));
        }
        break;
    }
}

在PHP中

print_r(
    $db->execute("SumeFunc(o)", array("name" => "test"))
);

错误

Array
(
    [errno] => -3
    [errmsg] => invoke failed: JS Error: ReferenceError: o is not defined nofile_a:0
    [ok] => 0
)

1 个答案:

答案 0 :(得分:7)

$db->execute(
    new MongoCode('SomeFunc(o)', array(
        'o' => array('name' => 'test') 
    ))
);