oximod 0.2.2

MongoDB ODM for Rust inspired by Mongoose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# OxiMod

<p align="center">
  <strong>Schema-aware MongoDB modeling for Rust</strong>
</p>

<p align="center">
  <img src="https://img.shields.io/crates/v/oximod">
  <img src="https://img.shields.io/crates/d/oximod">
  <img src="https://img.shields.io/badge/license-MIT-blue">
</p>

---

## Overview

OxiMod is a schema-based modeling layer for MongoDB, designed for Rust developers who want a more expressive way to define models without giving up direct access to the MongoDB driver.

Inspired by ODM-style workflows, OxiMod provides:

- derive-based schema configuration  
- builder-style model construction  
- validation and defaults  
- index declarations  
- typed model helpers  
- global and explicit-client workflows  
- optional lifecycle hooks  

At the same time, it preserves MongoDB’s native power by exposing:

- `mongodb::Collection<Self>`
- `mongodb::Collection<Document>`

OxiMod is best understood as:

> **MongoDB with stronger model ergonomics**, not a replacement for the driver.

---

## Design Philosophy

OxiMod is intentionally lightweight.

It focuses on areas that benefit from schema-awareness:

- model definition  
- builder construction  
- validation  
- defaults  
- index setup  
- optional lifecycle hooks  

For everything else, use the MongoDB driver directly:

- `Model::get_collection()`
- `Model::get_document_collection()`

This ensures:
- zero feature lock-in  
- full MongoDB flexibility  
- long-term maintainability  

---

## Builder API

```rust
let user = User::new()
    .name("Alice")
    .age(30)
    .active(true);
```

### Features

- accepts any `Into<T>`
- automatic conversions
- applies defaults
- supports optional + required fields
- customizable `_id` setter

---

## Model API

### Core

| Method | Description |
|------|------------|
| `save()` | Insert document |
| `save_mut()` | Insert document with mutable hooks |
| `clear()` | Remove all documents |
| `get_collection()` | Typed collection |
| `get_document_collection()` | Raw collection |

### Identity Helpers

| Method | Description |
|------|------------|
| `find_by_id()` | Fetch by `_id` |
| `update_by_id()` | Update by `_id` |
| `delete_by_id()` | Delete by `_id` |

### Utilities

| Method | Description |
|------|------------|
| `exists()` | Check existence |
| `count()` | Count documents |

---

## Client Usage

### Global

```rust
OxiClient::init_global(uri).await?;
user.save().await?;
```

### Explicit

```rust
user.save_from(&client).await?;
```

Used for:
- tests  
- multi-tenant apps  
- dependency injection  

---

## Collections

### Typed

```rust
let collection = User::get_collection()?;
```

### Raw

```rust
let collection = User::get_document_collection()?;
```

---

## Attributes

### Struct-Level

| Attribute | Description |
|----------|------------|
| `#[db("name")]` | Database |
| `#[collection("name")]` | Collection |
| `#[document_id_setter_ident("name")]` | Rename `_id` setter |
| `#[index_max_retries(N)]` | Retry count |
| `#[index_max_init_seconds(N)]` | Timeout |
| `#[hooks]` | Enable lifecycle hooks |

---

### Indexing

```rust
#[index(...)]
```

#### Core

| Attribute | Description |
|----------|------------|
| `unique` | Unique index |
| `sparse` | Skip missing |
| `hidden` | Hide index |
| `name = "..."` | Custom name |
| `order = 1/-1` | Sort order |
| `expire_after_secs` | TTL |

#### Advanced Types

| Attribute | Description |
|----------|------------|
| `text` | Text index |
| `hashed` | Hashed index |
| `geo_2dsphere` | Geo index |

#### Advanced Options

| Attribute | Description |
|----------|------------|
| `version` | Index version |
| `text_index_version` | Text version |
| `geo_2dsphere_index_version` | Geo version |
| `weight` | Text weight |
| `default_language` | Text language |
| `case_insensitive` | Collation |

---

## Validation

```rust
#[validate(...)]
```

### Length

| Validator | Description |
|----------|------------|
| `min_length` | Minimum |
| `max_length` | Maximum |
| `non_empty` | Not empty |

### String

| Validator | Description |
|----------|------------|
| `starts_with` | Prefix |
| `ends_with` | Suffix |
| `includes` | Contains |
| `alphanumeric` | ASCII |
| `email` | Email |
| `pattern` | Regex |

### Numeric

| Validator | Description |
|----------|------------|
| `min` / `max` | Range |
| `positive` | > 0 |
| `negative` | < 0 |
| `non_negative` | ≥ 0 |
| `non_positive` | ≤ 0 |

### Integer

| Validator | Description |
|----------|------------|
| `multiple_of` | Divisible |

### Optional

| Validator | Description |
|----------|------------|
| `required` | Not None |

### Custom

```rust
#[validate(custom(fn_name))]
```

---

## Defaults

```rust
#[default(...)]
```

Examples:

- `#[default("Guest".to_string())]`
- `#[default(42)]`
- `#[default(false)]`

---

## Hooks

```rust
#[hooks]
```

### Save Hooks

| Hook | Description |
|----------|------------|
| `pre_save` | Runs before `save()` |
| `post_save` | Runs after `save()` |
| `pre_save_mut` | Runs before `save_mut()` |
| `post_save_mut` | Runs after `save_mut()` |

### Query Hooks

| Hook | Description |
|----------|------------|
| `pre_find` | Runs before `find_by_id()` |
| `post_find` | Runs after `find_by_id()` |

### Mutation Hooks

| Hook | Description |
|----------|------------|
| `pre_update` | Runs before `update_by_id()` |
| `post_update` | Runs after `update_by_id()` |
| `pre_delete` | Runs before `delete_by_id()` |
| `post_delete` | Runs after `delete_by_id()` |

Hooks are optional and are enabled at the struct level with `#[hooks]`.

Hooks are implemented by implementing the `Hooks` trait for the model.

```rust
use oximod::{Hooks, Model};

#[derive(Model)]
#[db("app")]
#[collection("logs")]
#[hooks]
struct Log {
    message: String,
}

#[async_trait::async_trait]
impl Hooks for Log {
    async fn pre_save(&self) -> Result<(), oximod::OxiModError> {
        println!("Saving log");
        Ok(())
    }
}
```

Hooks are useful for:

- normalization
- logging
- validation beyond schema rules
- audit trails
- business rules
- event emission

---

## Example

```rust
use mongodb::bson::{doc, oid::ObjectId};
use oximod::{Model, OxiClient};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, Model)]
#[db("my_app_db")]
#[collection("users")]
struct User {
    #[serde(skip_serializing_if = "Option::is_none")]
    _id: Option<ObjectId>,

    #[index(unique, name = "email_idx")]
    #[validate(email)]
    email: String,

    #[validate(min_length = 3, max_length = 32)]
    name: String,

    #[validate(non_negative)]
    age: i32,

    #[default(false)]
    active: bool,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize global client
    dotenv::dotenv().ok();
    let uri = std::env::var("MONGODB_URI")?;
    OxiClient::init_global(uri).await?;

    // Clear collection
    User::clear().await?;

    // Build model using builder API
    let user = User::new()
        .email("alice@example.com")
        .name("Alice")
        .age(30)
        .active(true);

    // Save document
    let id = user.save().await?;
    println!("Inserted user: {}", id);

    // Find by id
    if let Some(found) = User::find_by_id(id).await? {
        println!("Found user: {}", found.name);
    }

    // Count documents
    let count = User::count(doc! {}).await?;
    println!("Total users: {}", count);

    // Use MongoDB driver directly
    let collection = User::get_collection()?;

    collection
        .update_one(
            doc! { "_id": id },
            doc! { "$set": { "active": false } },
        )
        .await?;

    println!("User updated");

    Ok(())
}
```

For more examples, feel free to check out the [`examples/`](https://github.com/arshia-eskandari/oximod/tree/main/oximod/examples) directory.

---

## Philosophy Summary

- minimal abstraction  
- maximum flexibility  
- compile-time safety  
- production-ready ergonomics  

---

## License

MIT