doctrine/mongodb-odm

ReferenceMany "must be of type array", but it's a Document/Collection

mustanggb opened this issue · 2 comments

Q A
Version 2.5.2

Support Question

I'm trying to use a package who's sample code uses ORM but modify it to work with ODM.

The original Entity field is:

    #[ORM\ManyToOne]
    #[ORM\JoinColumn(nullable: false)]
    private ?User $user = NULL;

Which I tried converting to a Document field as:

    #[MongoDB\ReferenceMany(targetDocument: User::class)]
    private $user = NULL;

However when performing a flush() gives the error message:

Doctrine\Common\Collections\ArrayCollection::__construct(): Argument #1 ($elements) must be of type array,
App\Document\User given, called invendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/UnitOfWork.php on line 611

I assume this is because it's triggering:

                // If $actualData[$name] is not a Collection then use an ArrayCollection.
                if (! $value instanceof Collection) {
                    $value = new ArrayCollection($value);
                }

It seems that $value is my User Document, should it somehow be a Collection instead?

It is mapped to a Collection as:

#[MongoDB\Document(collection: 'users')]
class User
{
    <snip>
}

Any guidance would be much appreciated.

If your document is supposed to have a link to one user, you should use MongoDB\ReferenceOne.

Please keep support question on StackOverflow under the doctrine-odm tag, we try to keep using Github solely for development purposes.

Doh, it's so obvious, thanks for your help.