doctrine / mongodb-odm

The Official PHP MongoDB ORM/ODM
https://www.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/
MIT License
1.09k stars 504 forks source link

@UniqueIndex does not work #1833

Closed Espinasse closed 6 years ago

Espinasse commented 6 years ago

Try to create index on mongodb colleciton but annotation seem not working.

/**
 * @ODM\Document(collection="user", repositoryClass="App\Repository\UserRepository")
 * @ODM\HasLifecycleCallbacks
 */
class UserDocument implements UserInterface, \Serializable, DocumentInterface
{
    /**
     * @var string
     * @ODM\Field(type="string")
     * @ODM\UniqueIndex
     */
    private $username;

Symfony version : 4.1 composer.json :

        "alcaeus/mongo-php-adapter": "^1.1",
        "doctrine/mongodb-odm-bundle": "^3.0",
Steveb-p commented 6 years ago

How exactly do you attempt to create indexes? You're using a command to update the collection schema?

Espinasse commented 6 years ago

I, thank for you reply :)

May be a image can be more expressive.

code

I just use annotation from Doctrine\ODM\MongoDB\Mapping\Annotations and try to make index by Document (above class definition) or above property class like $username for example. No one of this solution work. I dropped my collection with mongo cli and start a insert again but always same email or username is inserted

Steveb-p commented 6 years ago

Thought so. Remember that you need to actually call relevant commands to insert (actually build) indexes in collections. This is done so index checking does not take place every time you want to insert, update or remove a document. Once you think about it, it's perfectly obvious - after all, building an index can be a time consuming process, especially if you want to add new index to an already big collection.

You can see commands here(doctrine:mongodb:schema:create) and here(doctrine:mongodb:schema:update). Which are "proxies" to original commands: CreateCommand and UpdateCommand

Therefore, check if php app/console doctrine:mongodb:schema:update does the trick for you.

Espinasse commented 6 years ago

This solution is ok for me @Steveb-p thanks a lot :)