Search code examples
mongodbsymfonybidirectional

Add refrences to MongoDB schema within Symfony project


I'm trying to create MongoDB database with some references within Symfony. In my context I have 2 documents Customer and Meeting, One Customer can have Many Meeting so that what I did :

Meeting.php

<?php

namespace FrontOfficeBundle\Document;

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

/**
 * @MongoDB\Document
 */
class Meeting
{
    /**
     * @MongoDB\Id
     * @MongoDB\ReferenceOne(targetDocument="Customer")
     */
    protected $id;

    /**
     * @MongoDB\Field(type="timestamp")
     */
    protected $creationDate;

...

Customer.php

    <?php

namespace FrontOfficeBundle\Document;

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

/**
 * @MongoDB\Document
 */
class Customer
{
    /**
     * @MongoDB\Id()
     * @MongoDB\ReferenceMany(targetDocument="Meeting")
     */

    protected $id;

    /**
     * @MongoDB\Field(type="string")
     */
    protected $username;

...

and then when I run the command line:

php bin/console doctrine:mongodb:schema:update

I got :

No identifier/primary key specified for Document 'FrontOfficeBundle\Document\Meeting'. Every Document must have an identifier/primary key.

I tried by using @MongoDB\UniqueIndex() but no way. I think that @MongoDB\Id is supposed as an identifier !!!

Versions

  • Symfony 3.2
  • MongoDB 3.4.4

Any ideas ?

Thanks you.


Solution

  • Finally I found a solution, first I added a field called $meetings in the document Customer and an other $customer in the document meeting like this :

    Customer.php

    /**
     * @MongoDB\ReferenceMany(targetDocument="meeting", mappedBy="customer")
     */
    protected $meetings;
    

    Meeting.php

    /**
     * @MongoDB\ReferenceOne(targetDocument="customer", inversedBy="meetings")
     */
    protected $customer;
    

    Then run the command line to generate setters and getters:

    php bin/console doctrine:mongodb:generate:documents mybundleBundle

    And when I run a fixtures (Creating one customer then its meeting), everything work fine, you'll notice that the relationship 1 to many has been defined in your document (I'm using compass to display mongoDB) as a One-to-Squillions model (for more details about 1-to-N relationship : (https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1) that's mean the son document (meeting) contains the reference of the parent as shown below :

    Customer

    enter image description here

    Meeting

    enter image description here

    In MongoDB the @MongDB/Id is a primary key and the foreign key and never try to define references to this unique field.

    Thanks for your attention.