2
votes

I am checking json schema validation on the mongo layer using $jsonSchema. I need define a multilingual object. I use $ref. But I receive the error - $jsonSchema keyword 'definitions' is not currently supported According to the documentation it has to have a common json-schema behavior.

 async install(): Promise<void> {
        let db = await this.dbContainer.getDb();
        let properties = _.fromPairs(this.config.languages.map((language) => {
           return  [language, {$ref: '#/definitions/post'}]
        }));
        await db.createCollection(
            this.collectionName,
            {
                validator: {
                    $jsonSchema: {
                        bsonType: 'object',
                        required: ['title', 'summary', 'link'],
                        definitions: {
                            post: {
                                title: {
                                    bsonType: 'string',
                                    description: 'Title is required'
                                },
                                summary: {
                                    bsonType: 'string',
                                    description: 'Summary is required'
                                },
                                href: {
                                    bsonType: 'string',
                                    description: 'Summary is required'
                                },
                            },
                        },
                        properties,
                    }
                }
            }
        );

Does anybody has any suggestions? Should I use json-schema as a separated library?

2

2 Answers

2
votes

MongoDB has only implemented some of the JSON Schema specification.

If you want to make sure the JSON data in your database is always valid, it looks like you can't use definitions, and will have to copy / paste your schema parts.

Alterntativly, you could use JSON Schema before inserting your data into your database. However, you must consider the implications of potentially not having valid data (as defined by your schema) in the database if you allow writing to the database without using your JSON Schema.

Using JSON Schema in the database layer will do validation automatically, while doing validation on the application layer will require you to write code to do that for each type of thing you want to validate.

2
votes

JSON Schema as specification described here is similar but not the same as jsonSchema introduced in mongo.

In ommision section of mongo documentation, you can see that $ref is not supported.

enter image description here