Question

I'm new to both MongoDB and Lithium and I can't really find the "good way" of working with nested documents. I noticed that when I try

$user = Users::find('first' ... );
$user->somenewfield = array('key' => 'val');

what I get for "somenewfield" is a Document object. But there is also a DocumentArray class - what is the difference between them?

When I call

$user->save(); 

this results in Mongo (as expected):

"somenewfield" : { 
 "key": "value" 
}

OK, but when I later want to add a new key-value to the array and try

$user->somenewfield['newkey'] = 'newval';
var_dump($user->somenewfield->to('array')); // shows the old and the new key-value pairs
$user->save(); // does not work - the new pair is not added

What is the correct way to adding a new array to a document using lithium? What is the correct way of updating the array/adding new values to the array? Shall I alywas give a key for the array value?

Thanks for the help in advance. I'm kinda stuck ... reading the documentation, reading the code ... but at some points it gets difficult to find out everything alone :)

Edit: What I found at the end was that the way I shall use nested arrays is with $push and $pull:

Users::update(array('$push' => array('games' => (string) $game->_id)), 
  array(
    '_id' => $this->user()->_id, 
    'games' => array('$ne' => (string) $game->_id)), 
  array('atomic' => false));
Was it helpful?

Solution

I think there are some quirks in handling subdocuments, you can try:

$somenewfield = $user->somenewfield;
$somenewfield->newkey = newvalue;
$user->somenewfield = $somenewfield;
$user->save();

Or the alternative syntax:

$user->{'somenewfield.newkey'} = $newvalue;
$user->save();

You should be able to find more examples in the tests (look in tests/data at any tests for Document).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top