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 502 forks source link

Collection validator: JSON Schema #2233

Closed alexandre-abrioux closed 3 years ago

alexandre-abrioux commented 3 years ago

Feature Request

Q A
New Feature yes
RFC no
BC Break no

Summary

Hi,

I don't think it is currently possible to define a JSON schema to validate, on the database side, inserted or updated data. I am talking about the $jsonSchema operator of the validator expression: https://docs.mongodb.com/manual/core/schema-validation/#json-schema

Do you think that it would be something worth adding?

We could even generate that schema with all the metadata that we already have, with an option on the collection:

/**
 * @ODM\Document(
 *      collection="users",
 *      jsonSchemaValidator=true
 * )
 */

; or let the user specify the schema manually if needed:

/**
 * @ODM\Document(
 *      collection="users",
 *      jsonSchemaValidator=true,
 *      jsonSchema="{
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            }
        }"
 * )
 */

I think it could be a nice feature to have. If it is something that you would be interested in I could write a PR, I'm just asking for your opinion about that idea first. Let me know! :)

Thank you!

malarzm commented 3 years ago

@alexandre-abrioux this sound like a nice addition :) If you'd need any help feel free to ping me on our Slack's #mongodb-odm channel.

We could even generate that schema with all the metadata that we already have, with an option on the collection

I think for a first step we should go with user-defined jsonSchema, generating schema based on metadata can be added later. Also I expect schema-generation to be a can of worms if we get to single collection inheritance or discriminated embedded documents so I'd rather defer this until later date and not get you into bigger troubles :)

alexandre-abrioux commented 3 years ago

Thanks for the answer! I agree, let's do it by step. I'll start working on adding an user-defined jsonSchema and get back to you as soon as I have a working solution with tests. I'll check Slack if needed :)