π 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:
- Open the Atlas UI.
- In the left-hand menu, navigate to Network Settings and select "Database Access."
- 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.
- If the role is not atlasAdmin@admin, click "Edit" button next to the user.
- Scroll down to the Database User Privileges section and expand the Built-in Role dropdown.
- Select "Atlas admin" from the dropdown menu.
- 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
andisAdmin
. - 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 theuserSchema
object declared just above. - The
validationLevel
option specifies the level of validation to perform. This could bestrict
ormoderate
.- 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.
- If you set it to
- And finally, the
validationAction
option specifies the action to take when a document fails validation. This could beerror
orwarn
.- 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.
- If you set it to
Apply the schema to the users
collectionβ
You need to run the script to apply the schema to the users
collection.
-
Open a new terminal emulator tab in your GitHub codespace.
- Locate the bottom panel and click on the
TERMINAL
tab. - Locate the
+
icon on the top right of the terminal panel and click on it to open a new terminal tab. - Click on the new terminal tab to activate it.
- Locate the bottom panel and click on the
-
Run the following command to apply the schema to the
users
collection:cd server
npx tsx src/schema-validation/apply-schema.tsYou 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!
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.
- Open the file
server/src/schema-validation/test-validation.ts
file. - 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. - 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.