I am trying to retrieve the object from MongoDB but I am facing an issue that it is returning the element of base type instead of child and it is causing trouble, I figured out that it is somehow dependent on a property's value.
/**
* @MongoDB\Document(
* collection="zoo",
* repositoryClass="ZooRepository",
* )
*/
class Zoo
{
/**
* @MongoDB\ReferenceMany(targetDocument="Animal", inversedBy="zoo", strategy="addToSet")
* @var \Doctrine\Common\Collections\ArrayCollection
*/
protected $animals;
/**
* @return mixed
*/
public function getAnimals()
{
return $this->animals->toArray();
}
//Some more code
}
/**
* @MongoDB\Document(
* repositoryClass="AnimalRepository",
* collection="animals"
* )
* @MongoDB\InheritanceType("SINGLE_COLLECTION")
* @MongoDB\DiscriminatorField("discriminator")
* @MongoDB\DiscriminatorMap({
* "animal"="Animal",
* "birds"="Bird",
* "mamals"="Mamals"})
*/
class Animal
{
/**
* @MongoDB\ReferenceMany(targetDocument="Location", mappedBy="animals", simple=true, cascade={"persist"})
*
* @Assert\Count(min="0", max="1")
*/
protected $locations;
}
/**
* @MongoDB\Document(repositoryClass="AnimalRepository")
*/
class Bird extends Animal
{
}
/**
* @MongoDB\Document(repositoryClass="AnimalRepository")
*/
class Mamals extends Animal
{
}
The problem is: when I call getAnimals() from ZooHandler it returns the object of type Animal. What I want is the type of Mamals or Bird. The strange thing is, if I have an element in Animals->location then I got it right (Mamal/Bird) and if it does not have the element then I got the base type.
If I get the list of all Animals directly from AnimalRepository in AnimalHandler, I am getting the objects of Mamals/Bird accordingly.
EDITED: Zoo object
> db.zoo.findOne()
{
"_id" : ObjectId("5822bd23085f753b5a5a2408"),
"name" : "Zoo 2",
"active" : true,
"archived" : false,
"animals" : [
DBRef("animals", ObjectId("556cc7adec045b1a0c8b4567"),{ "$db": "tester", "discriminator": "Test\\Bundle\\Core\\Document\\Animal" }),
DBRef("animals", ObjectId("556cb3b0ec045bbf068b4582"),{ "$db": "tester", "discriminator": "Test\\Bundle\\Core\\Document\\Animal" })
]
}
For sure there are some more properties that are not shown, as they're irrelevant.