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);
Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.