|
| 1 | +import Screenshot from "@site/src/components/Screenshot"; |
1 | 2 | import Tabs from '@theme/Tabs';
|
2 | 3 | import TabItem from '@theme/TabItem';
|
3 | 4 |
|
@@ -60,7 +61,6 @@ The schema defines the following constraints:
|
60 | 61 |
|
61 | 62 | ## Explore the script to apply the schema
|
62 | 63 |
|
63 |
| - |
64 | 64 | <Tabs groupId="server">
|
65 | 65 | <TabItem value="node" label="🚀 NodeJS/Express">
|
66 | 66 |
|
@@ -91,39 +91,36 @@ The function uses the `db.command()` method to apply the schema to the `users` c
|
91 | 91 | </TabItem>
|
92 | 92 |
|
93 | 93 | <TabItem value="java" label="☕️ Java Spring Boot">
|
| 94 | +In this step, we’ll review the code that applies schema validation to the users collection. |
| 95 | +It’s already implemented in `SchemaValidationConfig.java` no changes needed. We’ll look at two methods: |
| 96 | +```java title='src/main/java/com/mongodb/devrel/library/infrastructure/config/SchemaValidationConfig.java' |
| 97 | +@Configuration |
| 98 | +public class SchemaValidationConfig { |
94 | 99 |
|
95 |
| -```java |
96 |
| -public void applySchemaValidation() { |
97 |
| - try (MongoClient mongoClient = MongoClients.create(mongoDBURI)) { |
98 |
| - MongoDatabase database = mongoClient.getDatabase("library"); |
99 |
| - |
100 |
| - Document userSchema = new Document("$jsonSchema", new Document() |
101 |
| - .append("bsonType", "object") |
102 |
| - .append("required", List.of("name", "isAdmin")) |
103 |
| - .append("properties", new Document() |
104 |
| - .append("name", new Document("bsonType", "string").append("minLength", 5) |
105 |
| - .append("description", "must be a string and is required")) |
106 |
| - .append("isAdmin", new Document("bsonType", "bool") |
107 |
| - .append("description", "must be a boolean and is required")) |
108 |
| - ) |
109 |
| - ); |
110 |
| - |
111 |
| - Document command = new Document("collMod", "users") |
112 |
| - .append("validator", userSchema) |
113 |
| - .append("validationLevel", "strict") |
114 |
| - .append("validationAction", "error"); |
115 |
| - |
116 |
| - Document result = database.runCommand(command); |
117 |
| - |
118 |
| - if (result.getDouble("ok") != 1.0) { |
119 |
| - System.err.println("Failed to enable schema validation!"); |
120 |
| - System.exit(1); |
121 |
| - } else { |
122 |
| - System.out.println("Schema validation enabled!"); |
123 |
| - } |
| 100 | + // fields .. |
| 101 | + |
| 102 | + private void applyUserSchema(MongoDatabase db) { |
| 103 | + // implementation |
| 104 | + } |
| 105 | + |
| 106 | + private void runCollMod(MongoDatabase db, String collection, Document schema) { |
| 107 | + // implementation |
124 | 108 | }
|
| 109 | + |
125 | 110 | }
|
126 | 111 | ```
|
| 112 | +- `applyUserSchema(MongoDatabase db)` |
| 113 | + - Ensures the users collection exists. |
| 114 | + - Builds a $jsonSchema requiring name (string, minLength: 5) and isAdmin (boolean). |
| 115 | + - Calls runCollMod(...) to attach the validator to the collection. |
| 116 | + |
| 117 | +- `runCollMod(MongoDatabase db, String collection, Document schema)` |
| 118 | + - Executes collMod with validator, validationLevel=strict, and validationAction=error. |
| 119 | + |
| 120 | + |
| 121 | + |
| 122 | +For readability, only the class structure is shown above. |
| 123 | +You can open the [SchemaValidationConfig](https://github.com/mongodb-developer/library-management-system/blob/java-server/java-server/src/main/java/com/mongodb/devrel/library/infrastructure/config/SchemaValidationConfig.java) in your project to review the complete implementation. |
127 | 124 |
|
128 | 125 | </TabItem>
|
129 | 126 | </Tabs>
|
@@ -164,24 +161,18 @@ You need to run the script to apply the schema to the `users` collection.
|
164 | 161 |
|
165 | 162 | <TabItem value="java" label="☕️ Java Spring Boot">
|
166 | 163 |
|
167 |
| -1. Stop the running app. |
168 |
| - 1. Locate the bottom panel and click on the `TERMINAL` tab. |
169 |
| - 1. Press Ctrl+C to interrup the running app |
170 |
| - |
171 |
| -1. Copy above code for `applySchemaValidation` as a method in the `LibraryApplication.java` class. |
172 |
| -1. Modify the `run` method to call `applySchemaValidation` |
173 |
| - ```java |
174 |
| - @Override |
175 |
| - public void run(String... args) { |
176 |
| - log.info("🚀 App Started"); |
177 |
| - applySchemaValidation(); |
178 |
| - } |
179 |
| - ``` |
180 |
| -1. Restart the app typing in the Terminal: |
| 164 | +The `applyUserSchema` method is triggered by the [execute](https://github.com/mongodb-developer/library-management-system/blob/java-server/java-server/src/main/java/com/mongodb/devrel/library/infrastructure/config/SchemaValidationConfig.java#L44) method, which runs only if the property `lab.schema-mode` is set. |
| 165 | +To apply the schema, you must set this property to **apply**. |
| 166 | + |
| 167 | +Stop the application if it’s running and restart it with: |
| 168 | + |
| 169 | +```java |
| 170 | +mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dlab.schema-mode=apply" |
| 171 | +``` |
| 172 | + |
| 173 | +When the application starts, you should see a message confirming that the validator was successfully applied to the users collection: |
| 174 | +<Screenshot url="https://github.com/mongodb-developer/library-management-system" src="img/screenshots/60-schema-validation/1-schema-applied.png" alt="The schema validation applied" /> |
181 | 175 |
|
182 |
| - ```bash |
183 |
| - mvn spring-boot:start |
184 |
| - ``` |
185 | 176 |
|
186 | 177 | </TabItem>
|
187 | 178 | </Tabs>
|
@@ -214,17 +205,18 @@ Modify the script to insert a document again with the `name` and `isAdmin` field
|
214 | 205 | </TabItem>
|
215 | 206 |
|
216 | 207 | <TabItem value="java" label="☕️ Java Spring Boot">
|
| 208 | +In this step, the schema is already created, and it’s time to test it. |
| 209 | +The [validateUserSchema](https://github.com/mongodb-developer/library-management-system/blob/java-server/java-server/src/main/java/com/mongodb/devrel/library/infrastructure/config/SchemaValidationConfig.java#L97) method, already implemented, tries to insert a new user without the isAdmin field. |
217 | 210 |
|
218 |
| -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, or you can check the Validation tab in Compass to check for the new validation rules. |
219 |
| - |
220 |
| -You can also check it in the mongosh typing: |
| 211 | +To trigger it, stop the application if it’s running and start it again with the property set to **test**: |
221 | 212 |
|
222 |
| -``` |
223 |
| -db.getCollectionInfos({ name: "users" }) |
| 213 | +```java |
| 214 | +mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dlab.schema-mode=test" |
224 | 215 | ```
|
225 | 216 |
|
226 |
| -If schema validation is not enabled, the "validator" field will be missing or empty. |
| 217 | +In the logs, you should see an error indicating that the insert was rejected by the validator: |
227 | 218 |
|
| 219 | +<Screenshot url="https://github.com/mongodb-developer/library-management-system" src="img/screenshots/60-schema-validation/2-schema-validated.png" alt="The schema validation applied" /> |
228 | 220 |
|
229 | 221 | </TabItem>
|
230 | 222 | </Tabs>
|
|
0 commit comments