Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you store an ObjectId while using Doctrine MongoDB ODM?

I want to store references manually instead of letting the ODM use the DBRef type.

I have the option of storing the _id I want to reference as a @String (for e.g - "4e18e625c2749a260e000024" ), but how do I store an instance of an ObjectId in this field instead?

new \MongoId("4e18e625c2749a260e000024") <-- what's the annotation for this type?

Saving it using a MongoId object instead of a string will save me half the space on this field. It's the same data type used by the @Id annotation, but the @Id can be used just once in a Document.

What' the right annotation to accomplish this?

like image 567
Dayson Avatar asked Jan 20 '23 06:01

Dayson


1 Answers

Update: There's now an official support for this type. Use @ObjectId or @Field(type="object_id") in your annotation to use the ObjectId / MongoId type. There's no need to use the solution below.

Also, use the latest master code from github.com/doctrine/mongodb-odm and avoid using the version on the website (it's out-dated).


Solution (deprecated)

Looks like there's no support for this yet. I discussed this issue on the IRC channel and opened a ticket for it here: https://github.com/doctrine/mongodb-odm/issues/125

A temporary fix would be to define a custom type and use an annotation like @Field(type="objectid") in your Document classes.

Here's the code for the custom type I'm using to accomplish this.

/**
 * Custom Data type to support the MongoId data type in fields
 */
class ObjectId extends \Doctrine\ODM\MongoDB\Mapping\Types\Type
{
    public function convertToDatabaseValue($value)
    {
        if ($value === null) {
            return null;
        }
        if ( ! $value instanceof \MongoId) {
            $value = new \MongoId($value);
        }
        return $value;
    }

    public function convertToPHPValue($value)
    {
        return $value !== null ? (string)$value : null;
    }
}

Register it using

\Doctrine\ODM\MongoDB\Mapping\Types\Type::addType('objectid', 'ObjectId' );
like image 65
Dayson Avatar answered Jan 25 '23 15:01

Dayson