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.
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.
Inserting a record that matches the criteria
When we insert a record that matches the validation criteria, the record will be inserted successfully.
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});
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.
Let’s execute the schema modification script via MongoDB shell:
Now we can insert the record with the value 1999 again
Success! As you can see, the schema has been successfully modified and the new record has been properly stored in the MongoDB database.
#