Validation in MongoDB

In Moon Modeler, you can easily draw MongoDB database structures and then generate schema validation scripts. Some validation rules are available in the user interface, additional rules can be defined textually.

How to set validation criteria

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.

MongoDB validation
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'
});

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});
MongoDB validation - success

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 validation - error

 #

Quick links

Download Buy Now!

Blog Categories
Blog by Platforms