doctrinedoctrine-odm

Doctrine documents can not be loaded if the ID strategy is NONE


I'm using Doctrine with MongoDB. Usually I don't care about the IDs but in one case I need the ID before the flush to avoid a needless roundtrip. So I added the ID strategy "NONE" and set the ID in the constructor. But after that I cannot load a document by its ID.

Code to load a document:

/* @var $userRepo DocumentRepository */
$userRepo = $managerRegistry->getRepository(User::class);
$qb = $userRepo->createQueryBuilder();
$qb->field('id')->in(['5cb6377ae0b68801bc3b1771']);
$user = $qb->getQuery()->execute()->getSingleResult();
var_dump($user instanceof User);

/* @var $userRepo DocumentRepository */
$userRepo = $managerRegistry->getRepository(User::class);
$users = $userRepo->findBy(['id' => '5cb6377ae0b68801bc3b1771']);
var_dump(count($users) === 1);

/* @var $userRepo DocumentRepository */
$userRepo = $managerRegistry->getRepository(User::class);
$user = $userRepo->find('5cb6377ae0b68801bc3b1771');
var_dump($user instanceof User);

(Actually false, false, false - Expected true, true, true)

Document:

/**
 * @ODM\Document
 */
class User
{

    /**
     * @ODM\Id(strategy="NONE")
     */
    protected $id;

    public function __construct()
    {
        $this->id = new \MongoId();
    }

    ...
}

Solution

  • This is happening because you're using a string in the find calls. You need to use MongoId as that's what your identifier is. So:

    /* @var $userRepo DocumentRepository */
    $userRepo = $managerRegistry->getRepository(User::class);
    $user = $userRepo->find(new \MongoId('5cb6377ae0b68801bc3b1771'));