MongoDB中存储的Javascript

时间:2013-07-28 00:01:27

标签: php javascript mongodb

我正在尝试使用存储的javascript在MongoDB中存储查询。

现在看起来像这样:

$collection = $db->$app_id;

$query = $collection->find( $filterQuery );

$db->system->js->save(array(
    "_id" => "qo8qu0",
    "value" => new MongoCode("function() { return array($query) }")
));

然后我执行它:

echo "<pre>";
print_r($test = $db->execute("qo8qu0()"));
echo "</pre>";

但是,我收到此错误: Catchable fatal error: Object of class MongoCursor could not be converted to string in /var/www/dev/classes/EmailMessaging.php on line 91

第91行是这一行(如上所述),  "value" => new MongoCode("function() { return array($filterQuery) }")

如果我使用count( $filterQuery );代替find( $filterQuery ); 它起作用并返回正确的数字。

如何使其工作,以便在使用find时返回数组?

谢谢

1 个答案:

答案 0 :(得分:0)

这是因为你的代码评估。它正在评估这个:

$query = $collection->find( $filterQuery );

因此$queryMongoCursor,然后您尝试将该类连接成一个字符串:

new MongoCode("function() { return array($query) }")

你需要像以下那样用eval完成整个事情:

return $this->execute('function(){ return db.collection.find(filter); }',  array('filter'=>array('_id'=>1)));

count有效,因为它会返回int,可以将其添加到字符串中。

修改

一种方式:

$db->system->js->save(array(
    "_id" => "qo8qu0",
    "value" => new MongoCode("function() { return db.collection.find(filter).toArray() }")
));

然后在你的应用中:

$test = $db->execute("qo8qu0()", array('filter'=>array('_id'=>1)))