I have the following definition of a MongoDB Document (I stripped down parts of the class for brevity):
// src/Acme/UserBundle/Document/User.php
namespace Acme\UserBundle\Document
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Bundle\MongoDBBundle\Validator\Constraints\Unique as MongoDBUnique;
/**
* @MongoDB\Document()
* @MongoDBUnique(fields="email", message="This email is already registered")
*/
class User implements UserInterface, EquatableInterface
{
/**
* @MongoDB\Id
*/
protected $id;
/**
* @MongoDB\String
* @Assert\Email(checkMX=true)
*/
protected $email;
/**
* @MongoDB\Collection
*/
protected $languages = array();
}
Next I generate the setters and getters with:
php app/console doctrine:mongodb:generate:documents UserBundle
I use the User class as usual, working everything fine, I can store instances of user that get correctly stored in mongodb.
Querying with the mongodb's console, I can see how the object is stored and that languages
stores an array:
> db.User.find()
{ "_id" : ObjectId("51c2da8d8b4d24315e9ec3d2"), "email" : "test@test.com", "languages" : [ "en", "fr" ] }
But when I try to retrieve the data:
$dm = $this->get('doctrine_mongodb')->getManager();
$user = $dm->getRepository('UserBundle:User')->findOneByEmail('test@test.com');
$user->getEmail()
returns the E-mail correctly but $user->getLanguages()
always return an empty array.
EDIT:
I managed to run a query using a CLI Command for app/console
:
$dm = $this->getContainer()->get('doctrine_mongodb')->getManager();
$user = $dm
->getRepository('UserBundle:User')
->findOneByEmail('test@test.com');
print_r($user->getLanguages());
And the output of the print_r
command was correct:
Array
(
[0] => en
[1] => fr
[2] => pt
[3] => es
)
EDIT2:
And after that I tried the application again and it worked normally. I don't know why.
I just had this problem and take a quick look at doctrine mongodb implementation.
Doctrine creates some hydrators classes at runtime (thanks to the class Doctrine\ODM\MongoDB\Hydrator\HydratorFactory
) and store the result in the cache. The cache is built on the first request then the cache is used. This is why you had this strange behaviour and resolution.
A simple reset of the cache solves this problem:
php app/console cache:clear