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?

0

3 Answers 3

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);
2
  • Downvote probably was given for eval(). There are cleaner ways to handle the json on the client side. e.g stackoverflow.com/questions/4935632/… Commented Nov 16, 2012 at 0:38
  • MongoDB doesn't support JSON.parse(), so eval is ok here. Commented Nov 16, 2012 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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.