π 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.
Explore the JSON schemaβ
- π NodeJS/Express
- βοΈ Java Spring Boot
The JSON schema for the users collection is stored in the server/src/schema-validation/apply-schema.ts file. Open the file and examine the schema.
JSON schema for the users collection:
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
nameandisAdmin. - The
namefield must be a string with a minimum length of five characters. - The
isAdminfield must be a boolean.
Explore the script to apply the schemaβ
- π NodeJS/Express
- βοΈ Java Spring Boot
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
collModoption specifies the collection to which the schema should be applied. - The
validatoroption specifies the JSON schema to use for validation. This is theuserSchemaobject declared just above. - The
validationLeveloption specifies the level of validation to perform. This could bestrictormoderate.- 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
validationActionoption specifies the action to take when a document fails validation. This could beerrororwarn.- 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
In this step, weβll review the code that applies schema validation to the users collection.
Itβs already implemented in SchemaValidationConfig.java no changes needed. Weβll look at two methods:
@Configuration
public class SchemaValidationConfig {
// fields ..
private void applyUserSchema(MongoDatabase db) {
// implementation
}
private void runCollMod(MongoDatabase db, String collection, Document schema) {
// implementation
}
}
-
applyUserSchema(MongoDatabase db)- Ensures the users collection exists.
- Builds a $jsonSchema requiring name (string, minLength: 5) and isAdmin (boolean).
- Calls runCollMod(...) to attach the validator to the collection.
-
runCollMod(MongoDatabase db, String collection, Document schema)- Executes collMod with validator, validationLevel=strict, and validationAction=error.
For readability, only the class structure is shown above. You can open the SchemaValidationConfig in your project to review the complete implementation.
Apply the schema to the users collectionβ
- π NodeJS/Express
- βοΈ Java Spring Boot
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
TERMINALtab. - 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
userscollection: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!
The applyUserSchema method is triggered by the execute method, which runs only if the property lab.schema-mode is set.
To apply the schema, you must set this property to apply.
Stop the application if itβs running and restart it with:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dlab.schema-mode=apply"
When the application starts, you should see a message confirming that the validator was successfully applied to the users collection:

Test the schema validationβ
- π NodeJS/Express
- βοΈ Java Spring Boot
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.tsfile. - 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.
In this step, the schema is already created, and itβs time to test it. The validateUserSchema method, already implemented, tries to insert a new user without the isAdmin field.
To trigger it, stop the application if itβs running and start it again with the property set to test:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dlab.schema-mode=test"
In the logs, you should see an error indicating that the insert was rejected by the validator:

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.