4

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?

2 Answers 2

9

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' );
0
0

Try:

/** @Id(strategy="NONE") */
1
  • I tried it. This doesn't work. It looks like you can use an @Id only once per document. Doesn't look like it supports this type. If I use this @Id with NONE strategy, then the primary identifier of the document stops working. Looks like it overrides behavior previously defined.
    – epicwhale
    Commented Jul 11, 2011 at 23:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.