MongoDB: How to Change the Validation Action

Updated: February 2, 2024 By: Guest Contributor Post a comment

Introduction

In MongoDB, data validation is essential for maintaining the integrity and consistency of the data stored in your database. MongoDB offers significant flexibility when it comes to data validation, allowing you to define validation rules for your collections and specify how strictly these rules should be enforced. In this tutorial, we’ll delve into changing the validation action for a MongoDB collection, transitioning between “warn” and “error” actions to suit your application’s needs.

Understanding Validation Rules

Before we jump into changing the validation action, it’s crucial to have a clear understanding of validation rules in MongoDB. Validation rules are defined using the JSON schema validation standard, which specifies the structure, type, and constraints of the documents within a collection.

{
   "$jsonSchema": {
     "bsonType": "object",
     "required": [ "name", "email" ],
     "properties": {
       "name": {
         "bsonType": "string",
         "description": "must be a string and is required"
       },
       "email": {
         "bsonType": "string",
         "pattern": "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
         "description": "must be a valid email address and is required"
       }
     }
   }
 }

Initial Collection Creation with Validation Rules

Let’s suppose we are establishing a new collection with specific validation rules.

db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: [ "name", "email" ],
      properties: {
        "name": {
          // Add name validation rules here
        },
        "email": {
          // Add email validation rules here
        }
      }
    }
  },
  validationLevel: "moderate",
  validationAction: "error"
})

As shown, you can specify the validation actions when you first create the collection. Here, the process terminates with an error if the inserted or updated document fails to meet the validation criteria.

Changing the Validation Action

There might be scenarios where you initially chose an “error” action but wish to switch to a “warn” to allow more flexibility during development. Or, conversely, you might want to tighten the controls by moving from “warn” to “error” for production. Changing the validation action is straightforward using the collMod command.

db.runCommand({
   collMod: "users",
   validationAction: "warn"
 })

This command changes the validation action of the “users” collection to “warn”. As a result, if a document violates the validation rules, MongoDB logs a warning message, but the operation proceeds.

Similarly, if you need to switch back to “error”, just rerun the collMod command with “error” as the value for validationAction.

db.runCommand({
   collMod: "users",
   validationAction: "error"
 })
 

Adjusting Validation Level

It’s also fruitful to explore the validation level option, which determines how MongoDB applies validation rules. The validation level can be “off”, “strict”, or “moderate”.

db.runCommand({
   collMod: "users",
   validationLevel: "moderate"
 })

This modifies the validation level to “moderate”, meaning validation rules are applied to inserts and to updates where the existing document already complies with the validation schema. This setting is particularly useful during transitional periods.

Practical Scenario

Consider a scenario where you’re working on an application that’s currently in the development phase, and you prefer the validation action to be set to “warn”. This allows developers to be alerted about validation rule violations without halting the development process. When the application transitions to production, you can switch the validation action to “error” to strictly enforce data integrity.

Conclusion

MongoDB’s data validation capabilities provide a powerful framework for ensuring data integrity and quality within your databases. Changing the validation action based on the current stage of your application (development or production) offers a flexible way to manage data validation. As we’ve demonstrated, altering the validation action and level to suit your needs is simple and can markedly impact your application’s data governance strategy. Always remember to meticulously plan and implement validation rules that serve your application’s requirements while maintaining flexibility and control over how data is inserted and updated.

Remember, the practice of data validation in MongoDB isn’t just about enforcing rules; it’s about ensuring the quality and reliability of the data your application relies on. Use the tools MongoDB provides to your advantage, tailoring them as your application evolves.