4
votes

I'm using the master branch of Doctrine MongoDB ODM and Symfony2 from the git repositories along with mongo extension 1.2.10.

I've created a number of classes/documents with annotations similar to:

namespace Acme\StoreBundle\Document;

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

/**
 * @MongoDB\Document
 */
class Person
{
    /**
     * @MongoDB\Id
     */
    protected $id;

    /**
     * @MongoDB\String(nullable=false)
     */
    protected $name;

    /**
     * @MongoDB\ReferenceOne(targetDocument="PersonType", inversedBy="person", nullable=false)
     */
    protected $personType;
}

When I create and persist a new document without setting the value or reference I receive no error. Am I misunderstanding the use of the nullable option and need to call validation code in the lifecycle callbacks, using the annotation incorrectly, or maybe a bug in Doctrine?

2
Of course it was the last link in my Google search... link I was assuming that the nullable option works the same as in the ORM, but it's actually controlling whether null values are stored in the database. Looks like I'll have to create some validation logic to enforce the constraint.CrEOF

2 Answers

2
votes

If you check out the annotation reference, setting nullable=false doesn't mean that it will fail validation on a null value.

From the docs:

nullable - By default, ODM will $unset fields in MongoDB if the PHP value is null. Specify true for this option to force ODM to store a null value in the database instead of unsetting the field.

1
votes

use Symfony\Component\Validator\Constraints as Assert;

/** * @mongodb\Field(name="name", type="string") * @Assert\NotBlank() */ private $name;

Hope you get the clue.