coen-hyde / Shanty-Mongo

Shanty Mongo is a mongodb library for the Zend Framework. Its intention is to make working with mongodb documents as natural and as simple as possible. In particular allowing embedded documents to also have custom document classes.
Other
200 stars 52 forks source link

Checking for embedded document existing #102

Open CrazyClicker opened 11 years ago

CrazyClicker commented 11 years ago

Hi! I'm new to Shanty_Mongo and Mongo itself so I got stuck.

I have a simple construction in my documents requirements

'products' => 'DocumentSet', 'products.$' => array('Document:Product'),

so when I add document to the set

$product = new Product($data = [....]); $this->products[15] = $product;

and then when I try to check product for existing

$this->products[11]; //returns empty Product class $this->products[20]; //returns null

How should I act to get model only on $this->products[15]?

coen-hyde commented 11 years ago

Hi,

I'm not exactly sure i know what you're asking but if you only want document 15 then you would do: $doc->products[15];

If you get an object back of class Product then the product exists. If you get back null then the document does not exist.

Cheers, Coen

CrazyClicker commented 11 years ago

I will try to explain.

When i set

$product = new Product($data = [....]); $this->products[5] = $product; $this->save();

my var_dump($this->products) looks like array(null,null,null,null,null, Object Product);

so when I try to call $this->products[2]; method Shanty_Mongo_DocumentSet::getProperty() returns empty object of Product class but not null. It is happenning because of line 54 of this class

if (array_key_exists($index, $this->_cleanData) ) $data = $this->_cleanData[$index];

there is no check for null value and method creates and returns new instance of a class. So i added is_null check

if (array_key_exists($index, $this->_cleanData) && !is_null($this->_cleanData[$index])) $data = $this->_cleanData[$index];

and it works as expected now (for me at least)

CrazyClicker commented 11 years ago

I can get correct result also if I use isset() function to check if property is really exists. It works pretty well for checking if properties with such requirements as 'DocumentSet' or 'Document' are really exist and not created 'on the fly' by getProperty methods.

It should be noticed in readmy prob.