Question: API Platform, mixed @EmbedOne() in mongoDB

Setup

I’m using mongoDB in API Platform and I created the following Attribute document:

/**
 * @ApiResource
 * @ODMDocument
 */
class Attribute
{
    /**
     * @ODMEmbedOne(
     *   discriminatorField="type",
     *   discriminatorMap={
     *     "string"=ValueString::class,
     *     "number"=ValueNumber::class
     *   },
     *   defaultDiscriminatorValue="string"
     * )
     */
    public $value;
}

The attribute document can embed one of the following EmbeddedDocuments:

/** @ODMEmbeddedDocument */
class ValueString
{
    /**
     * @ODMField
     */
    public $value;
}

or

/** @ODMEmbeddedDocument */
class ValueNumber
{
    /**
     * @ODMField(type="int")
     */
    public $value;
}

My goal with this is to be able to assign different value formats and data types to an Attributes value property. This is one of my reasons for using mongoDB.

Problem

However when I try to create an Attribute via a POST request I get the following error:

{
  "@context": "/contexts/Error",
  "@type": "hydra:Error",
  "hydra:title": "An error occurred",
  "hydra:description": "Argument 2 passed to SymfonyComponentSerializerSerializer::supportsDenormalization() must be of the type string, null given, called in /srv/api/vendor/symfony/serializer/Normalizer/AbstractObjectNormalizer.php on line 434",
  "trace": [
...
}

Possible solution

After debugging I found out that the problem is caused by the targetDocument property not being set in the DoctrineODMMongoDBMappingClassMetadata. I tried to fix this by listening to the Doctrine ODM loadClassMetadata event and manually setting the targetDocument (possibly based on some specified request property like ‘type’).

The problem with this solution however is that the targetDocument of the $value property is only set once. Because this property can accept multiple Embedded documents and thus multiple targetDocuments this is not a viable solution.

My Question

Whats the best way to have different embedded documents in a single property in API Platform with mongoDB? Does API Platform even support this @EmbedOne properly and did I even configure it correctly? Thank you.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *