π¦ΈββοΈ Enable Validation for the Authors Collection
In this exercise, you will define a JSON schema for the authors collection, apply the schema to the collection, and test the schema validation by inserting a document that does not match the schema.
This is an advanced exercise that requires you to write code. If you get stuck and you're doing this during a live workshop, you can flag down an instructor in the room for help.
- π NodeJS/Express
- βοΈ Java Spring Boot
- Start by opening the
server/src/schema-validation/apply-schema.ts
file in your GitHub codespace and uncomment lines 41-61. - Complete the tasks marked with
// TODO
comments. - Execute the script again to apply the schema to the
authors
collection.cd server
npx tsx src/schema-validation/apply-schema.ts - Finally, test the schema validation by modifying the
server/src/schema-validation/test-validation.ts
script. Inserting a document in theauthors
collection.
In this advanced exercise, you will extend the SchemaValidationConfig class to support the authors collection.
Two methods are already defined in the class, but both are left with // TODO
markers for you to implement:
private void applyAuthorSchema(MongoDatabase db) {
// TODO: Implement the schema for authors ($jsonSchema with required 'name', 'bio', etc.)
}
private void validateAuthorsSchema(MongoDatabase db) {
// TODO: Insert an invalid document to assert rejection (e.g., missing or short 'name')
}
Once implemented, you can run the application with the right target and mode:
- Apply the schema to authors
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dlab.schema-mode=apply -Dlab.schema-target=authors"
- Test the schema validation for authors
mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dlab.schema-mode=test -Dlab.schema-target=authors"
When you run in apply mode, you should see logs confirming the schema was applied. When you run in test mode, the invalid insert should fail, proving the validation works.