Another part of my working on moving Medusa v2 to Medusa v4 is, after reading this excellent article, to see about adding schema validation to our MongoDB collections.  For some collections, the schema is simple, but for some collections like the one for users, we are looking at roughly 60 fields, some of which would be JSON fields in a database such as PostgreSQL, because of their having sometimes complex subfields. And adding schema validation to such collections would help assure that our code fills in required fields, and fields with the proper type of data. Unfortunately, the article only talks about using Laravel migrations for new databases, and does not show how to add or maintain them on existing databases.

Sadly, Google has not been of much help either. The search term "laravel migration add mongodb schema validation to database" turned up nothing of help, and the AI content was wrong. It read:

<?php

use Illuminate\Database\Migrations\Migration;
use MongoDB\Laravel\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddSchemaValidationToMyCollection extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('my_collection', function (Blueprint $collection) {
            $collection->validator([
                '$jsonSchema' => [
                    'bsonType' => 'object',
                    'required' => ['name', 'email'],
                    'properties' => [
                        'name' => [
                            'bsonType' => 'string',
                            'description' => 'must be a string and is required'
                        ],
                        'email' => [
                            'bsonType' => 'string',
                            'pattern' => '^.+@.+$',
                            'description' => 'must be a string and match the email pattern'
                        ],
                        'age' => [
                            'bsonType' => 'int',
                            'minimum' => 18,
                            'description' => 'must be an integer and at least 18'
                        ]
                    ]
                ]
            ]);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('my_collection', function (Blueprint $collection) {
            // To remove schema validation, set the validator to an empty object
            $collection->validator([]);
        });
    }
}

Unfortunately, the Blueprint class does not include the validator() method. Then, the Google search for "laravel database migration mongodb alter table to alter validation schema" is no better. It returns similar results with the AI content of:
 

    use Illuminate\Database\Migrations\Migration;
    use MongoDB\Laravel\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;

    class UpdateUsersValidationSchema extends Migration
    {
        public function up(): void
        {
            Schema::table('users', function (Blueprint $collection) {
                $collection->setSchemaValidation([
                    'validator' => [
                        '$jsonSchema' => [
                            'bsonType' => 'object',
                            'required' => ['name', 'email'],
                            'properties' => [
                                'name' => [
                                    'bsonType' => 'string',
                                    'description' => 'must be a string and is required'
                                ],
                                'email' => [
                                    'bsonType' => 'string',
                                    'pattern' => '^.+@.+\..+$',
                                    'description' => 'must be a string and match the email pattern'
                                ],
                                // Add or modify other fields and their validation rules
                            ]
                        ]
                    ],
                    'validationLevel' => 'strict', // or 'moderate', 'off'
                    'validationAction' => 'error'  // or 'warn'
                ]);
            });
        }

        public function down(): void
        {
            // Define the logic to revert the schema validation if needed
            // This might involve setting a less strict validation or removing it
            Schema::table('users', function (Blueprint $collection) {
                $collection->setSchemaValidation([]); // Example: Remove validation
            });
        }
    }


Both of these got a thumbs down for not being correct. And a third search which I do not remember was talking about issuing raw commands to MongoDB, but like the other two results, there  was no method which the results were referencing. 

But all is not lost.  I contacted the author of the article, explained my dilemma, and he has contacts with the MongoDB folks... so stay tuned... he may come up with something to write another article about, and the documentation for the laravel-mongodb 
documentation may even get an update, in which case, I will certainly post about it when I see it!

(And note...why quote the big blobs of code? So I can come back, reference this, and see what I found to be wrong, rather than going "Oh, why didn't I try this before?" when I obviously did...LOL)

Categories