Validation in MongoDB

In Moon Modeler, you can easily draw MongoDB database structures and

How to set validation criteria

Some validation rules are available in the user interface, additional rules can be defined textually.

Step 1 – make sure you set the Validation level and Validation action values in the Collection specifics section.

Step 2 – set the validation criteria to the Validation input field (2) in the selected field that belongs to the selected collection.

Validation settings for MongoDB database defined in Moon Modeler

Here is the schema validation script generated by Moon Modeler

db.createCollection('traffic', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      title: 'traffic',
      properties: {
        source: {
          enum: ['campaign', 'website', null]
        },
        year: {
          bsonType: 'int',
          minimum: 2000,
          maximum: 2100
        }
      }
    }
  },
  validationLevel: 'strict',
  validationAction: 'error'
});

Running the validation script using MongoDB Shell

The MongoDB shell can be downloaded from the MongoDB website. You can download it, install and then interact with your MongoDB database. Run the validation script in the MongoDB shell.

MongoDB Shell and execution of schema validation script defined in Moon Modeler

Inserting a record that matches the criteria

When we insert a record that matches the validation criteria, the record will be inserted successfully.

MongoDB shell and inserting a record that matches schema validation criteria
db.traffic.insertOne({source: "website", year: 2023});

Inserting a record that does not match the criteria

But in case the record contains a value that does not match the validation criteria, you will receive an error message.

The following command contains the value 1999 for the year field. This value is below the minimum criteria and therefore the validation will produce the error message displayed on the screenshot below.

db.traffic.insertOne({source: "website", year: 1999});
MongoDB shell and inserting a record that does not match schema validation criteria

Updating the schema

You can modify the database structure and validation criteria in your project and then generate a modification script. The following screenshot shows the modification script with updated validation criteria.

Moon Modeler and MongoDB schema modification script.

Let’s execute the schema modification script via MongoDB shell:

MongoDB shell and execution of schema modification script.

Now we can insert the record with the value 1999 again

MongoDB shell and inserting a record to the modified MongoDB schema.

Success! As you can see, the schema has been successfully modified and the new record has been properly stored in the MongoDB database.

#

DATA MODELING TOOLS
DRAW Diagrams and
GENERATE Scripts
Download data modeling tools
Blog Categories
Blog by Platforms