How do you store ObjectId when using Doctrine MongoDB ODM?

I want to save the links manually instead of letting ODM use the DBRef type.

I have the option to save the _id that I want to refer to as @String (for example, โ€œ4e18e625c2749a260e000024โ€), but how do I save the ObjectId instance in this field?

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

Saving it using the MongoId object instead of a string will cause me to get a space in this field. This is the same data type used by the @Id annotation, but @Id can only be used once in a document.

What is the โ€œcorrect annotationโ€ for this?

+4
source share
2 answers

Update: Now official support for this type. Use @ObjectId or @Field(type="object_id") in your annotation to use the ObjectId / MongoId type. No need to use the solution below.

Also, use the latest master code from github.com/doctrine/mongodb-odm and do not use the version on the website (this is deprecated).


Solution (deprecated)

There seems to be no support yet. I discussed this issue on the IRC channel and opened a ticket for him: https://github.com/doctrine/mongodb-odm/issues/125

A temporary fix will be to define a custom type and use annotation like @Field(type="objectid") in the document classes.

Here is the code for the custom type that I use to execute 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' ); 
+9
source

Try:

 /** @Id(strategy="NONE") */ 
0
source

All Articles