Skip to content

Commit da81bcc

Browse files
Merge pull request #98 from monarch-orm/docs-improvements
Improve documentation details
2 parents 5e177cd + b066102 commit da81bcc

8 files changed

Lines changed: 204 additions & 134 deletions

File tree

docs/.vitepress/config.mts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,10 @@ export default defineConfig({
1616
text: "Guide",
1717
items: [
1818
{ text: "Getting Started", link: "/guide/getting-started" },
19-
{ text: "Schemas & Types", link: "/guide/schemas-and-types" },
20-
{ text: "Queries & Operators", link: "/guide/queries-and-operators" },
21-
{ text: "Advanced Schemas", link: "/guide/advanced-schemas" },
19+
{ text: "Schemas", link: "/guide/schemas" },
20+
{ text: "Types", link: "/guide/types" },
21+
{ text: "Queries", link: "/guide/queries" },
22+
{ text: "Operators", link: "/guide/operators" },
2223
{ text: "Aggregations & Relations", link: "/guide/aggregation-and-relations" },
2324
],
2425
},

docs/guide/aggregation-and-relations.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ const PostSchema = createSchema("posts", {
2424
});
2525

2626
const schemas = defineSchemas({
27-
users: UserSchema,
28-
posts: PostSchema,
27+
UserSchema,
28+
PostSchema,
2929
});
3030

3131
// Configure the relationships

docs/guide/getting-started.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ const UserSchema = createSchema("users", {
3434

3535
const client = createClient(/** db uri **/)
3636
const schemas = defineSchemas({
37-
users: UserSchema,
37+
UserSchema,
3838
});
3939

4040
const { collections } = createDatabase(client.db(), schemas);
@@ -69,7 +69,7 @@ It is good practice to assign your `defineSchemas` result to a variable (e.g. `s
6969

7070
```typescript
7171
const schemas = defineSchemas({
72-
users: UserSchema,
72+
UserSchema,
7373
});
7474

7575
const { collections } = createDatabase(client.db(), schemas);
@@ -157,7 +157,7 @@ const UserSchema = createSchema("users", {
157157
isVerified: boolean(),
158158
});
159159

160-
const monarchDb = createDatabase(client.db(), defineSchemas({ users: UserSchema }));
160+
const monarchDb = createDatabase(client.db(), defineSchemas({ UserSchema }));
161161
const UserModel = monarchDb.use(UserSchema);
162162
export default UserModel;
163163
```

docs/guide/operators.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Operators
2+
3+
Monarch provides typed wrapper functions for standard MongoDB query operators. These functions enforce strict type safety and ensure your queries align with your inferred schemas seamlessly.
4+
5+
You can import them from `monarch-orm/operators`.
6+
7+
```typescript
8+
import { eq, gt, or, inArray } from "monarch-orm/operators";
9+
```
10+
11+
## Comparison Operators
12+
13+
- **`eq(value)`**: Matches values equal to the specified value.
14+
- **`neq(value)`**: Matches values not equal to the specified value.
15+
- **`gt(value)`**: Matches values greater than the specified value.
16+
- **`lt(value)`**: Matches values less than the specified value.
17+
- **`gte(value)`**: Matches values greater than or equal to the specified value.
18+
- **`lte(value)`**: Matches values less than or equal to the specified value.
19+
20+
```typescript
21+
const adults = await db.collections.users.find({
22+
age: gte(18)
23+
});
24+
```
25+
26+
## Logical Operators
27+
28+
- **`and(...expressions)`**: Matches documents that satisfy all expressions.
29+
- **`or(...expressions)`**: Matches documents that satisfy at least one expression.
30+
- **`nor(...expressions)`**: Matches documents that fail all expressions.
31+
- **`not(expression)`**: Inverts the effect of a filter expression.
32+
33+
```typescript
34+
const specificUsers = await db.collections.users.find(
35+
or(
36+
{ age: lt(18) },
37+
{ isVerified: false }
38+
)
39+
);
40+
```
41+
42+
## Array Operators
43+
44+
- **`inArray(values)`**: Matches values that exist in the specified array.
45+
- **`notInArray(values)`**: Matches values that do not exist in the specified array.
46+
- **`size(value)`**: Matches arrays with the specified number of elements.
47+
48+
```typescript
49+
const targetedUsers = await db.collections.users.find({
50+
role: inArray(["admin", "moderator"])
51+
});
52+
```
53+
54+
## Element Operators
55+
56+
- **`exists()`**: Matches documents where the field exists.
57+
- **`notExists()`**: Matches documents where the field does not exist.
58+
59+
```typescript
60+
const usersWithPhone = await db.collections.users.find({
61+
phoneNumber: exists()
62+
});
63+
```

docs/guide/queries-and-operators.md

Lines changed: 0 additions & 122 deletions
This file was deleted.

docs/guide/queries.md

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
# Queries
2+
3+
Monarch ORM provides a powerful, type-safe API for querying your MongoDB collections. By using the query builders, you can construct complex filters without losing type safety.
4+
5+
## Query Modifiers and Immutability
6+
7+
When you use `.find()` or `.findOne()`, Monarch returns a lazy query builder. The query is not executed until you `await` it. This allows you to chain modifiers to shape your results.
8+
9+
> [!IMPORTANT]
10+
> Query modifier methods (`.select()`, `.sort()`, `.limit()`, etc.) **do not mutate** the original query instance. Instead, they return a **new** instance of the query builder.
11+
12+
This immutability makes it incredibly safe to re-use base queries throughout your application without unintended side effects.
13+
14+
```typescript
15+
// Define a base query
16+
const activeUsersQuery = db.collections.users.find({ isVerified: true });
17+
18+
// Safely reuse the base query for different purposes
19+
const allActiveUsers = await activeUsersQuery;
20+
21+
// This returns a NEW query instance, leaving `activeUsersQuery` untouched
22+
const paginatedUsers = await activeUsersQuery.limit(10).skip(20);
23+
24+
// You can still use the original query without the limit/skip side effects
25+
const activeUserCount = await activeUsersQuery.count();
26+
```
27+
28+
## Nested Fields and Dot Notation
29+
30+
Because Monarch uses the official MongoDB driver's typings under the hood, you get full type safety when querying nested object fields using either dot notation or standard nested object structures.
31+
32+
```typescript
33+
import { createSchema } from "monarch-orm";
34+
import { object, string } from "monarch-orm/types";
35+
36+
// Define a schema with a nested object
37+
const UserSchema = createSchema("users", {
38+
name: string(),
39+
address: object({
40+
city: string(),
41+
zip: string()
42+
})
43+
});
44+
45+
// Using a standard nested object structure
46+
const usersInNewYorkNested = await db.collections.users.find({
47+
address: {
48+
city: "New York" // fully typed!
49+
}
50+
});
51+
52+
// Or using dot notation
53+
const usersInNewYorkDot = await db.collections.users.find({
54+
"address.city": "New York"
55+
});
56+
57+
```
58+
59+
The TypeScript compiler will correctly enforce the types for both nested properties and nested objects, ensuring you don't query a nested number field with a string or misspell the path (e.g., `"address.town"` or `{ address: { town: "..." } }` will throw a type error).
60+
61+
62+
## Selecting & Omitting Fields
63+
64+
You can control exactly which fields are returned from the database using `.select()` and `.omit()`.
65+
66+
```typescript
67+
// Only return the name and email fields
68+
const users = await db.collections.users
69+
.find()
70+
.select({ name: true, email: true });
71+
72+
// Return everything EXCEPT the age and password fields
73+
const publicUsers = await db.collections.users
74+
.find()
75+
.omit({ age: true, password: true });
76+
```
77+
78+
## Sorting, Limiting, and Skipping
79+
80+
Use these modifiers to paginate and order your results.
81+
82+
```typescript
83+
const latestUsers = await db.collections.users
84+
.find({ isVerified: true })
85+
.sort({ createdAt: -1 }) // Sort descending by createdAt
86+
.limit(10) // Return max 10 documents
87+
.skip(20); // Skip the first 20 documents
88+
```
89+
90+
## Cursors
91+
92+
For large datasets where you don't want to load everything into memory at once, you can use `.cursor()` to iterate over documents one by one.
93+
94+
```typescript
95+
const cursor = await db.collections.users.find({ isVerified: true }).cursor();
96+
97+
for await (const user of cursor) {
98+
console.log(user.name);
99+
}
100+
```
101+
102+
## Native MongoDB Syntax
103+
104+
Because Monarch wraps the underlying MongoDB Node.js driver, you are still free to use native MongoDB query syntax if you prefer. The fields and operators are fully typed based on your schema.
105+
106+
> [!TIP]
107+
> Alternatively, you can use our built-in [Helper Operators](/guide/operators) which provide even stronger type safety and schema inference.
108+
109+
```typescript
110+
const activeUsers = await db.collections.users.find({
111+
age: { $gte: 18 },
112+
role: { $in: ["admin", "moderator"] }
113+
});
114+
```
Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,20 @@
1-
# Advanced Schemas
1+
# Schemas
22

3-
Monarch ORM provides advanced capabilities to shape the data returned by your queries, add indexes reliably to records, and group schema structures effectively in large applications.
3+
Monarch provides a rich set of schema builders to strictly enforce your MongoDB documents structure.
4+
5+
## Creating Schemas
6+
7+
Use `createSchema` to initialize a schema for a given collection name.
8+
9+
```typescript
10+
import { createSchema } from "monarch-orm";
11+
import { string, number } from "monarch-orm/types";
12+
13+
const UserSchema = createSchema("users", {
14+
name: string().required(),
15+
age: number().optional(),
16+
});
17+
```
418

519
## Virtuals
620

@@ -19,7 +33,7 @@ const UserSchema = createSchema("users", {
1933
role: virtual("isAdmin", ({ isAdmin }) => (isAdmin ? "admin" : "user")),
2034
});
2135

22-
const schemas = defineSchemas({ users: UserSchema });
36+
const schemas = defineSchemas({ UserSchema });
2337
const db = createDatabase(client.db(), schemas);
2438
const user = await db.collections.users.insertOne({ name: "Tom", age: 30, isAdmin: true });
2539

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Schemas & Types
1+
# Types
22

33
Monarch provides a rich set of schema builders to strictly enforce your MongoDB documents structure.
44

0 commit comments

Comments
 (0)