简体   繁体   中英

Find request with MongoDB/CakePHP return id:null

I need to run a simple request with cakePHP and a MongoDB database. I use ichikaway/cakephp-mongodb plugin. The insertions are ok but this simple request :

$this->Category->find('first', array('conditions' => array('name_cat' =>  "Cars")));

Give me :

array('Category' => array('id' => null))        

But "Cars" is in my database :

{
    "_id" : ObjectId("54ad46e919d056cc7b483430"),
    "facebook_id" : "1",
    "name_cat" : "Cars"
} 

I have already tested to add "hint" parameter or to define $primaryKey in the model but the result is the same.

Thanks for your help.

EDIT :

After some researchs I found that the last Item of every request "find" is replaced by an Item with an id:null. If I have 2 items "Cars" in my database :

$this->Category->find('All', array("conditions" => array("name_cat" => "Cars")));

Give me :

array(
(int) 0 => array(
    'Category' => array(
        'facebook_id' => '1',
        'name_cat' => 'Cars',
        'id' => '54ad46e919d056cc7b483430'
    )
),
(int) 1 => array(
    'Category' => array(
        'id' => null
    )
)

)

I looked in the plugin source code and found that the MongoCursor::getNext() function give me NULL for the last item. This function is called in read() function, after the execution of the request.

So I used iterator_to_array() function and the result is good.

Old code in MogodbSource.php (lines 1168 to 1180)

while ($return->hasNext()) {
    $mongodata = $return->getNext();
    [...]
}

New Code :

$cursor_mongo = iterator_to_array($return);
foreach ($cursor_mongo as $mongodata) {
    [...]
}

This new code is working for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM