I'm trying to serialize embedded mongodb documents with JMSSerizial Bundle
Asked Answered
S

1

7

I'm try to serialize a MongoDB document with embedded documents within Symfony 2.1. I am using the JMSserializer and Mongodb-odm bundles.

I have the following Documents entities.

// Blog

namespace App\DocumentBundle\Document;

use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use JMS\SerializerBundle\Annotation\Type;

/**
 * @MongoDB\Document(repositoryClass="App\DocumentBundle\Repository\BlogRepository")
 */
class Blog {

    /**
     * @MongoDB\Id
     */
    protected $id;

    /**
     * @MongoDB\String
     * @Assert\NotBlank()
     */
    protected $title;

    /**
     * @MongoDB\string
     * @Assert\NotBlank()
     */
    protected $blog;

    /**
     * @MongoDB\EmbedMany(targetDocument="Tag")
     */
    private $tags;

    /**
     * @MongoDB\Timestamp
     */
    protected $created;

    /**
     * @MongoDB\Timestamp
     */
    protected $updated;
}

and

// Tag

namespace App\DocumentBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\EmbeddedDocument
 */
class Tag {

    /**
     * @MongoDB\String
     */
    protected $name;
}

An ArrayCollection type is generated for the tag attribute, but the JMSSerializer bundle doesn't like it. If I change the tag to @MongoDB\String and regenerate the Blog document, then serialization occurs, but not with @MongoDB\EmbedMany(targetDocument="Tag") set.

Do I need to specify some of the JMSSerializer annotated attributes allow embedded document to also be serialized?

Surrebuttal answered 8/11, 2012 at 7:5 Comment(3)
Your code seems fine. Are you using the latest versions of the bundles? Also what do you mean by that JMSSerializer does not like it? What is the error message thrown?Peewit
why not annotate $tags with @MongoDB\Collection if you're storing nothing more than tag names? you'll end up with tags: ['tag1', 'tag2', 'tag3', 'etc']Reprobation
try to specify type to ArrayCollection with annotations jmsyst.com/libs/serializer/master/reference/annotations#typeParkins
P
1

You have to configure the expected type for JMSSerializer

Annotation :

/**
 * @MongoDB\EmbedMany(targetDocument="Tag")
 * @Type(ArrayCollection<App\DocumentBundle\Document\Tag>)
 */
private $tags;

Yaml :

tags:
    expose: true
    type: ArrayCollection<App\DocumentBundle\Document\Tag>
Pogge answered 7/1, 2014 at 11:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.