Skip to content

Commit f49e624

Browse files
committed
Added validation and compound indexes
1 parent 0db3367 commit f49e624

File tree

4 files changed

+182
-10
lines changed

4 files changed

+182
-10
lines changed

docs/50-demo-app/3-configure.mdx

+13
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,21 @@ mvn spring-boot:run
6363

6464
In the *Terminal* tab at the bottom, look for the `Server is running on port: 5000` line. If you see it, you're good to go!
6565

66+
<Tabs groupId="server">
67+
<TabItem value="node" label="🚀 NodeJS/Express">
68+
6669
<Screenshot url="https://github.com/mongodb-developer/library-management-system" src="img/screenshots/50-demo-app/3-configure/1-running.png" alt="The terminal panel" />
6770

71+
</TabItem>
72+
73+
<TabItem value="java" label="☕️ Java Spring Boot">
74+
75+
<Screenshot url="https://github.com/mongodb-developer/library-management-system" src="img/screenshots/50-demo-app/3-configure/1-running-java.png" alt="The terminal panel" />
76+
77+
</TabItem>
78+
</Tabs>
79+
80+
6881
## Reload the client
6982

7083
Now that the server is running, you can reload the client to see the application.

docs/60-schema-validation/2-validate-users.mdx

+112-4
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1+
import Tabs from '@theme/Tabs';
2+
import TabItem from '@theme/TabItem';
3+
14
# 👐 Enable Validation for the Users Collection
25

36
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.
47

5-
:::info
6-
Note for Java users: schema validation rules are typically applied via a Javascript script! Although there's nothing stopping us to write this code in Java, this is usually a DB Admin task.
7-
:::
8-
98
## Database user permissions
109

1110
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:
@@ -22,8 +21,20 @@ Atlas will deploy the change in a few seconds.
2221

2322
## Explore the JSON schema
2423

24+
<Tabs groupId="server">
25+
<TabItem value="node" label="🚀 NodeJS/Express">
26+
2527
The JSON schema for the `users` collection is stored in the `server/src/schema-validation/apply-schema.ts` [file](https://github.com/mongodb-developer/library-management-system/blob/main/server/src/schema-validation/apply-schema.ts). Open the file in your GitHub codespace and examine the schema.
2628

29+
</TabItem>
30+
31+
<TabItem value="java" label="☕️ Java Spring Boot">
32+
33+
JSON schema for the `users` collection:
34+
35+
</TabItem>
36+
</Tabs>
37+
2738
```ts
2839
const userSchema = {
2940
bsonType: 'object',
@@ -49,6 +60,10 @@ The schema defines the following constraints:
4960

5061
## Explore the script to apply the schema
5162

63+
64+
<Tabs groupId="server">
65+
<TabItem value="node" label="🚀 NodeJS/Express">
66+
5267
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.
5368

5469
```js
@@ -73,8 +88,51 @@ The function uses the `db.command()` method to apply the schema to the `users` c
7388
- If you set it to `error`, MongoDB rejects any insert or update that violates the validation criteria.
7489
- If you set it to `warn`, the operation proceeds, but the violation is recorded in the MongoDB log.
7590

91+
</TabItem>
92+
93+
<TabItem value="java" label="☕️ Java Spring Boot">
94+
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+
}
124+
}
125+
}
126+
```
127+
128+
</TabItem>
129+
</Tabs>
130+
76131
## Apply the schema to the `users` collection
77132

133+
<Tabs groupId="server">
134+
<TabItem value="node" label="🚀 NodeJS/Express">
135+
78136
You need to run the script to apply the schema to the `users` collection.
79137

80138
1. Open a new terminal emulator tab in your GitHub codespace.
@@ -102,12 +160,42 @@ You need to run the script to apply the schema to the `users` collection.
102160
Schema validation enabled!
103161
```
104162

163+
</TabItem>
164+
165+
<TabItem value="java" label="☕️ Java Spring Boot">
166+
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:
181+
182+
```bash
183+
mvn spring-boot:start
184+
```
185+
186+
</TabItem>
187+
</Tabs>
188+
189+
105190
:::caution
106191
If you see an error related to your user permissions, go back to the [Database User Permissions](#database-user-permissions) section and update your user permissions.
107192
:::
108193

109194
## Test the schema validation
110195

196+
<Tabs groupId="server">
197+
<TabItem value="node" label="🚀 NodeJS/Express">
198+
111199
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.
112200

113201
1. Open the file `server/src/schema-validation/test-validation.ts` [file](https://github.com/mongodb-developer/library-management-system/blob/main/server/src/schema-validation/test-validation.ts).
@@ -122,6 +210,26 @@ The error describes that the `name` and `isAdmin` fields are required but missin
122210

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

213+
214+
</TabItem>
215+
216+
<TabItem value="java" label="☕️ Java Spring Boot">
217+
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:
221+
222+
```
223+
db.getCollectionInfos({ name: "users" })
224+
```
225+
226+
If schema validation is not enabled, the "validator" field will be missing or empty.
227+
228+
229+
</TabItem>
230+
</Tabs>
231+
232+
125233
## Summary
126234

127235
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.

docs/70-indexing/1-create-compound-index.mdx

+57-6
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
1-
# 👐 Build a compound index following the ESR rule
1+
import Tabs from '@theme/Tabs';
2+
import TabItem from '@theme/TabItem';
23

3-
:::info
4-
Note for Java users: we will create indexes via a Javascript script! Although there's nothing stopping us to write this code in Java, this is usually a DB Admin task.
5-
:::
4+
# 👐 Build a compound index following the ESR rule
65

76
In this exercise, you will build a compound index following the ESR rule, compare the query explain plans before and after creating the index, and analyze them.
87

98
## Explore the code
109

10+
11+
<Tabs groupId="server">
12+
<TabItem value="node" label="🚀 NodeJS/Express">
13+
1114
1. Open the file `server/src/indexing/borrowed-books-index.ts` [file](https://github.com/mongodb-developer/library-management-system/blob/main/server/src/indexing/borrowed-books-index.ts) in your GitHub Codespace.
1215

13-
2. Examine the code to build a compound index on the `borrowedBooks` collection.
16+
2. Examine the code to build a compound index on the `issueDetails` collection.
1417

1518
```js
1619
/**
@@ -33,7 +36,7 @@ In this exercise, you will build a compound index following the ESR rule, compar
3336
```
3437
3538
:::info
36-
The index is created on the `borrowedBooks` collection to support the query that finds the issue details for a user with a specific `userID`, where the `borrowDate` is greater than or equal to a specific `date`, and sorts the results by `returnedDate` in descending order.
39+
The index is created on the `issueDetails` collection to support the query that finds the issue details for a user with a specific `userID`, where the `borrowDate` is greater than or equal to a specific `date`, and sorts the results by `returnedDate` in descending order.
3740
3841
This is compound index and it follows the ESR rule: Equality, Sort, and Range. This ensures optimal performance for the query.
3942
:::
@@ -73,6 +76,54 @@ In this exercise, you will build a compound index following the ESR rule, compar
7376
Notice the difference in the winning plan stage and the number of documents examined before and after creating the index.
7477
:::
7578

79+
80+
</TabItem>
81+
82+
<TabItem value="java" label="☕️ Java Spring Boot">
83+
84+
1. Open the file `java-server/java-server/src/main/java/com/mongodb/devrel/library/model/IssueDetail.java` [file](https://github.com/mongodb-developer/library-management-system/blob/java-server/java-server/src/main/java/com/mongodb/devrel/library/model/IssueDetail.java) in your GitHub Codespace.
85+
86+
1. Examine the code to build a compound index on the `issueDetails` collection.
87+
88+
```java
89+
// add these imports
90+
import org.springframework.data.mongodb.core.index.Indexed;
91+
import org.springframework.data.mongodb.core.index.CompoundIndex;
92+
93+
// ...
94+
// Add the CompoundIndex annotation
95+
@CompoundIndex(name = "user_returned_borrow_idx", def = "{'user._id': 1, 'returnedDate': 1, 'borrowDate': 1}")
96+
public class IssueDetail {
97+
// ...
98+
99+
// Constructors, Getters, Setters
100+
}
101+
```
102+
103+
:::info
104+
The index is created on the `issueDetails` collection to support the query that finds the issue details for a user with a specific `userID`, where the `borrowDate` is greater than or equal to a specific `date`, and sorts the results by `returnedDate` in descending order.
105+
106+
This is compound index and it follows the ESR rule: Equality, Sort, and Range. This ensures optimal performance for the query.
107+
:::
108+
1. Add to `application.properties` this line to enable automatic creation of indexes
109+
110+
```
111+
spring.data.mongodb.auto-index-creation=true
112+
```
113+
1. Stop the running app.
114+
1. Locate the bottom panel and click on the `TERMINAL` tab.
115+
1. Press Ctrl+C to interrup the running app
116+
117+
1. Restart the app typing in the Terminal:
118+
119+
```bash
120+
mvn spring-boot:start
121+
```
122+
123+
</TabItem>
124+
</Tabs>
125+
126+
76127
## 🦸‍♀️ Try different indexes
77128

78129
Modify the compound index by adding and removing fields, and observe the changes in the query explain plans.
Loading

0 commit comments

Comments
 (0)