1

I have a collection of offers and complicated query with a lot of fields and sorting. The task is to find a previous and next documents in the query results having only a query array and current document ID. So I'm writing a javascript function that performs a query with sorting and returns two IDs. The problem is to convert php query array into a correct javascript object.

Something like this, for example:

$query = array('city' => new MongoId('...'), 'price' => array('$gt' => 100000), ...);
$sort = array('price' => -1);
$code = new MongoCode("function findPrevNext() { db.offer.find($query).sort($sort).forEach(function(obj){ ... }) }");

How can I make such conversion?

Lisio
  • 1,571
  • 2
  • 15
  • 22

3 Answers3

1

To read this data in your JavaScript, run JavaScript's eval() function on the JSON echoed from PHP.

Edit: There was another answer from someone else here, where they discussed the usage of json_encode() in PHP.

For your array conversion to JSON you would:

json_encode($my_array);

To parse that data into a JavaScript object you would:

var myObject = eval(jsonStringFromPHP);
27A
  • 105
  • 1
  • 7
  • Downvote probably was given for eval(). There are cleaner ways to handle the json on the client side. e.g http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript – Michel Feldheim Nov 16 '12 at 00:38
  • MongoDB doesn't support JSON.parse(), so eval is ok here. – Lisio Nov 16 '12 at 12:27
1

If you run with PHP >= 5.3.0, you can use json_encode and can take advantage of options parameter.

json_encode($array, JSON_FORCE_OBJECT);

JSON_FORCE_OBJECT

Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty.

Wahyu Kristianto
  • 8,719
  • 6
  • 43
  • 68
0

There is no need to use conversion at all. Everything can be done using standard tools:

$code = 'function findNext(query, sort, current) { ... }';
$result = $mongo->command(array('$eval' => new MongoCode($code), 'args' => array($query, $sort, new MongoId($offer)), 'nolock' => true));
Lisio
  • 1,571
  • 2
  • 15
  • 22