Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB PHP: How do I get ObjectId with a JSON feed? (it's blank)

I'm storing a file through GridFS and saving the id like so:

$file_id = $gridfs->storeUpload('texture');
$item = array(
    'name'=>$_POST['name'],
    'description'=>$_POST['description'],
    'price'=>$_POST['price'],
    'categories'=>$category_array,
    'tags'=>$tag_array,
    'file'=>$file_id
 );
 $collection->insert($item);

and through terminal and doing find() "file" returns: ObjectId("4cbe9afe460890b774110000")

If i do this to create a JSON feed so i can get info back for my application "file" is blank... why is this?:

foreach($cursor as $item){
            $return[$i] = array(
                'name'=>$item['name'],
                'description'=>$item['description'],
                'file'=>$item['file']
            );
            $i++;
        }
        echo json_encode($return);

The strange thing, to me, is why can I do:

foreach($cursor as $item){
echo $item['file'];
}

and get it back tho?

Oh, and here is what the feed returns:

[{"name":"Tea Stained Paper 1","description":"Grungy paper texture stained with tea and coffee.","file":{}},{"name":"Worn Metal 1","description":"A grooved, worn old metal texture","file":{}}]
like image 560
Oscar Godson Avatar asked Oct 20 '10 08:10

Oscar Godson


2 Answers

Not sure, but maybe

echo json_encode($return, JSON_FORCE_OBJECT);

is what you need to do.

It also could be, that you need to convert $item['file'] to utf8

utf8_encode($item['file']);

before assigning it to the $return array.

like image 163
JochenJung Avatar answered Nov 15 '22 12:11

JochenJung


MongoIds keep their values tucked away in an invisible field. It has no visible fields, so there's nothing to convert to JSON, hence {}. If you'd like to have json_encode do the "right" thing, vote for http://jira.mongodb.org/browse/PHP-154.

Echoing a MongoId converts it to a string, that's why it behaves differently.

like image 28
kristina Avatar answered Nov 15 '22 10:11

kristina