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

Impossible to unset a field when the type is object_id #2537

Open olivier34000 opened 1 year ago

olivier34000 commented 1 year ago

BC Break Report

Q A
BC Break yes
Version 2.1

Summary

I have a document with a field with the type object_id. I try to unset this field with the query builder and a exception is thrown.

Previous behavior

In the 1.3 version it worked but I think because the driver was less strict.

Current behavior

How to reproduce

Add a field in the document User

+    /**
+     * @ODM\Field(type="object_id")
+     *
+     * @var string|null
+     */
+    protected $identifier;
+

Now we can add test in the class BuilderTest


+    public function testUnset2Field(): void
+    {
+        $qb = $this->getTestQueryBuilder()
+            ->updateOne()
+            ->field('identifier')->unsetField()
+            ->field('username')->equals('boo');
+
+        $expected = ['username' => 'boo'];
+        self::assertEquals($expected, $qb->getQueryArray());
+
+        $expected = [
+            '$unset' => ['identifier' => 1],
+        ];
+        self::assertEquals($expected, $qb->getNewObj());
+    }

The error

1) Doctrine\ODM\MongoDB\Tests\Query\BuilderTest::testUnset2Field                                          
TypeError: MongoDB\BSON\ObjectId::__construct(): Argument #1 ($id) must be of type ?string, int given     
malarzm commented 1 year ago

Thanks for the report! Scheduling for the next bugfix version.

I believe the bug lies somewhere in \Doctrine\ODM\MongoDB\Persisters\DocumentPersister::prepareQueryOrNewObj as ODM tries to prepare a query, sees identifier field and tries to case it to its type.