2

I have inheritance document with type SINGLE_COLLECTION configured in my Symfony 4.4 app. When i run command bin/console doctrine:mongodb:schema:create, then error occurs a collection 'db.Person' already exists.

Everything was done according to the documentation: https://www.doctrine-project.org/projects/doctrine-mongodb-odm/en/2.0/reference/inheritance-mapping.html#single-collection-inheritance

src/Document/Person.php

<?php

namespace App\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\Document
 * @MongoDB\InheritanceType("SINGLE_COLLECTION")
 * @MongoDB\DiscriminatorField("type")
 * @MongoDB\DiscriminatorMap({"person"=Person::class, "employee"=Employee::class})
 */
class Person
{
    /**
     * @var integer|null
     *
     * @MongoDB\Id
     */
    protected $id;

    /**
     * @var string|null
     *
     * @MongoDB\Field(type="string")
     */
    protected $name;
}

src/Document/Employee.php

<?php

namespace App\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\Document
 */
class Employee extends Person
{

    /**
     * @var string|null
     *
     * @MongoDB\Field(type="string")
     */
    protected $grade;
}

It looks like command is trying to create DB collection for every Document class, ignoring declaration of SINGLE_COLLECTION type.

How to fix it?

Mateusz K.
  • 111
  • 6
  • Collections in MongoDB do not need to be explicitly created. What is the failing operation exactly? – D. SM May 05 '20 at 14:48
  • I'know that it is not needed, but I prefer to create full DB schema for indexes. Extended error response is: `MongoDB\Driver\Exception\CommandException: a collection 'db.Person' already exists in vendor/mongodb/mongodb/src/Operation/CreateCollection.php:222` – Mateusz K. May 05 '20 at 14:56
  • What is the complete stack trace? – D. SM May 05 '20 at 15:05
  • Oleg, I cannot get stacktrace. When I run `bin/console doctrine:mongodb:schema:create -vvv` I got a response: `a collection 'db.Person' already exists` `Created indexes for all classes` – Mateusz K. May 06 '20 at 08:25

1 Answers1

2

ODM's odm:schema:create is iterating through all metadatas and tries to create a collection without considering possible relations between them. A proper fix would be in the ODM's SchemaManager to either check whether a collection exists prior to creating or catching exception and ignoring it in case of existing collection.

I have created https://github.com/doctrine/mongodb-odm/issues/2182 to track this issue. If you have some time to spare we will appreciate a PR!

malarzm
  • 2,831
  • 2
  • 15
  • 25