MongoDB and PHP looses _id when inserting 2 objects
Some stran开发者_StackOverflow社区ge Problem:
I have an Object with properties, if one propertie is altough an object witch already has an "_id", mongoDB does not create an "_id" for the first object?
// convert properties to array
$save = $this->model->toArray();
foreach ($save as $key => $val) {
// value is an object, convert to array
if ($val instanceof NcX_Mongo_Model) {
$save[$key] = $val->toArray();
}
}
// update
if ($this->model->getId()) {
$this->collection->save($save);
} else {
error_log('insert');
// insert
$this->collection->insert($save);
}
more code..:
$event = new My_Model_Mongo_Event();
$location = new My_Model_Mongo_Location();
$event->setLocation($location);
$event->save();
// no id set
$event->setLocation($location->toArray());
$event->save();
// everything works.. and id is set to event
Got it, i have no clue why but when doing this:
// update
if ($this->model->getId()) {
$this->collection->save($save);
} else {
// insert
$this->collection->insert($save);
// if i dont do this, the model has no id when inserting 2 objects
$this->model->setId($save['_id']);
}
The ID is set, it sounds logical but it works without "setId" when only inserting an plain array.
精彩评论