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

API Platform - Subresources: Cannot use reference for lookup or graphLookup: dbRef references are not supported (MongoDB-Symfony6.2) #2495

Closed sayou closed 1 year ago

sayou commented 1 year ago
Q A
Version 4.5

Support Question

I am currently working on programming a website using Symfony version 6.2 and API Platform in addition to MongoDB (version v6.0.3) in the database.

I try to use the Subresources and I followed the official documentation of the API Platform: https://api-platform.com/docs/core/subresources/

I tried to use exactly what is written on the documentation (this is the code):

#[ApiResource(
    uriTemplate: '/companies/{companyId}/employees',
    operations: [ new GetCollection() ]
    uriVariables: [
        'companyId' => new Link(toProperty: 'company', fromClass: Company::class),
    ]
)]
class Employee
{
    #[MongoDB\Id()]
    private string $id;

    #[MongoDB\Field(type: Type::STRING)]
    private string $name;

    #[MongoDB\ReferenceOne(targetDocument: Company::class, inversedBy: "employees")]
    private ?Company $company;

    public function getId()
    {
        return $this->id;
    }
}

and for the Company class:

#[ApiResource]
class Company
{
    #[MongoDB\Id()]
    public string $id;

    #[MongoDB\Field(type: Type::STRING)]
    public string $name;

    #[MongoDB\ReferenceMany(targetDocument: Employee::class, mappedBy: "company")]
    /** @var Employee[] */
    #[Link(toProperty: 'company')]
    public $employees = [];
}

but while using the Postman to get the result from /companies/{companyId}/employees, this error message appears:

"Cannot use reference 'company' in class 'App\\Document\\Company' for lookup or graphLookup: dbRef references are not supported." Is there any solution to that?

Steveb-p commented 1 year ago

You need to use a different referencing strategy: https://www.doctrine-project.org/projects/doctrine-mongodb-odm/en/2.3/reference/reference-mapping.html#storing-references

malarzm commented 1 year ago

Exactly what @Steveb-p wrote :) The only thing I'd like to add that not supporting DBRef objects is not a shortcoming of ODM, but MongoDB itself.