Skip to main content

πŸ‘ Enable Validation for the Users Collection

In this exercise, you will explore the pre-written JSON validation schema for the users collection, run a script to apply it to the collection, and test the schema validation by inserting a document that does not match the schema.

Database user permissions​

To update the validator for any database collection, your database user must have admin privileges. Follow these steps to ensure your user has the correct permissions:

  1. Open the Atlas UI.
  2. In the left-hand menu, navigate to Network Settings and select "Database Access."
  3. Locate your database user in the list. Check the MongoDB Roles column for the role of the user you are using for this workshop. If the role is not atlasAdmin@admin, you will need to update it.
  4. If the role is not atlasAdmin@admin, click "Edit" button next to the user.
  5. Scroll down to the Database User Privileges section and expand the Built-in Role dropdown.
  6. Select "Atlas admin" from the dropdown menu.
  7. Click "Update User" to save the changes.

Atlas will deploy the change in a few seconds.

Explore the JSON schema​

The JSON schema for the users collection is stored in the server/src/schema-validation/apply-schema.ts file. Open the file in your GitHub codespace and examine the schema.

const userSchema = {
bsonType: 'object',
required: ['name', 'isAdmin'],
properties: {
name: {
bsonType: 'string',
minLength: 5,
description: 'must be a string and is required'
},
isAdmin: {
bsonType: 'bool',
description: 'must be a boolean and is required'
}
}
};

The schema defines the following constraints:

  • The required fields are name and isAdmin.
  • The name field must be a string with a minimum length of five characters.
  • The isAdmin field must be a boolean.

Explore the script to apply the schema​

Examine the lines immediately following the schema definition in the apply-schema.ts file. You will see a function that applies the schema to the users collection.

console.log('Applying schema validation for users...');
const resultUsers = await db.command({
collMod: 'users',
validator: {
$jsonSchema: userSchema
},
validationLevel: 'strict',
validationAction: 'error'
});

The function uses the db.command() method to apply the schema to the users collection.

  • The collMod option specifies the collection to which the schema should be applied.
  • The validator option specifies the JSON schema to use for validation. This is the userSchema object declared just above.
  • The validationLevel option specifies the level of validation to perform. This could be strict or moderate.
    • If you set it to strict, the document will be inserted and updated only if it passes validation.
    • If you set it to moderate, updates to existing documents in the collection that don't match the validation rules aren't checked for validity.
  • And finally, the validationAction option specifies the action to take when a document fails validation. This could be error or warn.
    • If you set it to error, MongoDB rejects any insert or update that violates the validation criteria.
    • If you set it to warn, the operation proceeds, but the violation is recorded in the MongoDB log.

Apply the schema to the users collection​

You need to run the script to apply the schema to the users collection.

  1. Open a new terminal emulator tab in your GitHub codespace.

    1. Locate the bottom panel and click on the TERMINAL tab.
    2. Locate the + icon on the top right of the terminal panel and click on it to open a new terminal tab.
    3. Click on the new terminal tab to activate it.
  2. Run the following command to apply the schema to the users collection:

    cd server
    npx tsx src/schema-validation/apply-schema.ts

    You might be prompted to allow pasting into the terminal. Click "Allow" to paste the command.

    Click "Enter" to run the command. After a few seconds, you should see the following output:

    Connecting to MongoDB Atlas...
    Connected!

    Applying schema validation for users...
    Schema validation enabled!
caution

If you see an error related to your user permissions, go back to the Database User Permissions section and update your user permissions.

Test the schema validation​

Now that the schema validation is enabled for the users collection, you can test it by inserting a document that does not match the schema.

  1. Open the file server/src/schema-validation/test-validation.ts file.
  2. Explore the call to the insertOne() function around line 12 that will try to insert a new user and the error handling code around line 18.
  3. Execute the script by running the following command.
npx tsx src/schema-validation/test-validation.ts

The error describes that the name and isAdmin fields are required but missing in the document you tried to insert.

Modify the script to insert a document again with the name and isAdmin fields and you should see the document inserted successfully.

Summary​

In this exercise, you explored the JSON schema for the users collection, ran a script to apply the schema to the collection, and tested the schema validation by inserting a document that does not match the schema.

In the next exercise, you will enable schema validation for the authors collection.