doctrine/mongodb-odm — Issue #270: ReferenceOne/Many doesn't find objects if there is no targetDocument set
Author: Wedgybo
Created: 2012-03-07 01:08:28+00:00
State: open

Running against the latest master.

```PHP
/**
* @MongoDB\Document(collection="statistics")
*/
class Statistic extends DomainModel
{

/** @MongoDB\ReferenceOne */
protected $reference;

/** @MongoDB\String */
protected $type;

/** @MongoDB\EmbedMany(targetDocument="StatPoint") */
protected $values;

}

/** @MongoDB\Document(collection="companies") */
class Company extends DomainModel implements Compliant
{
/** @MongoDB\ReferenceOne(targetDocument="Statistic", mappedBy="reference") */
protected $compliancePoints;
}
```
When using $company->getCompliancePoints()->getValues(); the object Statistic is never found.

The problem appears to be in the DocumentPersister.php file prepareQueryElement() method.

Here's a quick hack to get the query working again (The field name doesn't change the reference.id to reference.$id to find the right object). I'd appreciate if someone could tell me if this is the root of the problem? This was working before I updated to the latest code and common 2.2.

```PHP
if (isset($mapping['targetDocument'])) {
$targetClass = $this->dm->getClassMetadata($mapping['targetDocument']);
if ($targetClass->hasField($e[1])) {
if ($targetClass->identifier === $e[1]) {
$fieldName = $e[0] . '.$id';
if ($prepareValue === true) {
if (is_array($value)) {
$keys = array_keys($value);
if (isset($keys[0][0]) && $keys[0][0] === $this->cmd) {
foreach ($value[$keys[0]] as $k => $v) {
$value[$keys[0]][$k] = $targetClass->getDatabaseIdentifierValue($v);
}
} else {
foreach ($value as $k => $v) {
$value[$k] = $targetClass->getDatabaseIdentifierValue($v);
}
}
} else {
$value = $targetClass->getDatabaseIdentifierValue($value);
}
}

} else {
$targetMapping = $targetClass->getFieldMapping($e[1]);
$e[1] = $targetMapping['name'];
$fieldName = $e[0] . '.' . $e[1];

if (count($e) > 2) {
unset($e[0], $e[1]);
$key = implode('.', $e);

if (isset($targetMapping['targetDocument'])) {
$nextTargetClass = $this->dm->getClassMetadata($targetMapping['targetDocument']);
$value = $this->prepareQueryElement($key, $value, $nextTargetClass, $prepareValue);
} else {
$value = $this->prepareQueryElement($key, $value, null, $prepareValue);
}

$fieldName .= '.' . $key;
}
}
}
// We are referencing another Document, we just don't know which one yet.
} elseif (isset($mapping['reference']) && $mapping['reference'] == true) {
// Fix the query to reference an actual MongoId
$fieldName = $e[0] . '.$id';
}
```