1
votes

This is my first time shoving objects into Mongo - I am using PHP. I know that MongoDB adds the _id variable to an array while inserting using the MongoCollection::insert() function. the problem is this:

if I define a public variable named _id the variable remains NULL upon insert

class MognoTest {
    public _id;
    public foo;

    public function __construct(){
        $this->foo = 'bar';
    }
}

$obj = new MongoTest();
$Mongo->collection->insert($obj);
var_dump($obj)
$found_obj = $Mongo->collection->findOne();
var_dump($found_obj);

The var_dump()s on $obj and $found_obj both return an object with _id=NULL. If I comment out _id in the class definition, the code runs properly and both var_dump()s print a MongoID.

I want to define in the class an _id to make my code clearer and make my code hinting on Netbeans work properly. Is there something I am overlooking?

1
Have you tried setting the value for _id before inserting it into the database?maialithar
I plan on using the MongoID auto-generated by the MongoDB as my primary key and I'll be using in my code later on.Rhett N. Lowe

1 Answers

0
votes

Ok, so I got a solution, though i don't like it to be honest -- to me it seems inelegant.

class MognoTest {
    public _id;
    public foo;

    public function __construct($load = NULL){
        $this->foo = 'bar';
        if ($load != NULL && isset($load['_id']))
            $this->_id = $load['_id'];
    }
    public function insertPrep(){
        if ($this->_id === NULL)
            unset($this->_id);
    }
}

//create object, prep, insert
$obj = new MongoTest();
$obj->insertPrep();
$Mongo->collection->insert($obj);
var_dump($obj)

//get object back and reload as object
$found_obj = $Mongo->collection->findOne();
$new_obj = new MongoTest($found_obj);
var_dump($new_obj);

I consider this solution inelegant because the programmer must now remember to add a line of code before each insert MongoTest::insertPrep(). I also tried adding a public function __insert() magic function but that didn't pan out :(

I still look for a better solution. But for anyone with this problem, here is a fix even if this fix isn't the elegant one I was hoping for.