Search code examples
phpmongodbdoctrinedoctrine-odm

Why does MongoID generate different values?


I have a a relational database with a user table and has user id's etc. However the commenting system is stored in Mongo and

$author = new Author();
$userID = 1;
$author->setId( new \MongoId( $userID ) ); <--- different ID generated everytime

$discussion = new Discussion();
             $discussion->setCreatedAt(new \DateTime());
             $discussion->setAuthor($author);

The ID that is generated is different every time so I have values like 5082a694253b4a1201000000, 5082a55e253b4a1f05000000.

How do I relate back to the user ID for example user ID 1? Or should just forget the whole new MongoID business and just store the user ID in the document?


Solution

  • From the documentation:

    public MongoId::__construct ([ string $id = NULL ] )

    $id: A string to use as the id. Must be 24 hexidecimal characters. If an invalid string is passed to this constructor, the constructor will ignore it and create a new id value.

    So that's why, even if you give an id to the MongoId, it doesn't fit into a 24 hexidecimal characters. So MongoId ignore it and generate a new one.

    I think you just need to define the UserId as it is:

    $author = new Author();
    $author->setUserId($userID);