How to create a JSON channel from the MongoDB collection

I create a CMS for my client to work with my photos and sell them on my site. For the end of the CMS and the front end, where both will be all AJAX, it would be nice to get the JSON channel set up so that I can use the same channel to create new β€œpages” and β€œviews” using JS.

So, this sample channel will look like {[name: 'A Photo', description: 'lorem ipsum ...'], [...]}, and then with jQuery or JS I can create a table of all his photos, pages etc. How can I customize this for myself?

Should I just create a PHP file that gets all the data from MongoDB, put it in an array, than convert the array to JSON?

+3
source share
3 answers
$cursor = $this->collection->find($params); $return = array(); $i=0; while( $cursor->hasNext() ) { $return[$i] = $cursor->getNext(); // key() function returns the records '_id' $return[$i++]['_id'] = $cursor->key(); } return json_encode($return); 

This is how I return JSON from Mongo.

+9
source

I did it as follows:

 $cursor = $collection->find($params); if($cursor->hasNext()) { return json_encode(iterator_to_array($cursor)); } 

If you need _ids, check this answer to see why you are not getting it: MongoDB PHP: How do I get an ObjectId using a JSON channel? (it's empty)

+1
source

This is what I do:

 $data = json_decode(json_encode(iterator_to_array($cursor, true))); 

Thus, I am sure that I have an array of objects that you can correctly call:

 foreach($data as $doc){ echo 'title:'.$doc->title.'<br>'; } 
0
source

Source: https://habr.com/ru/post/904209/


All Articles