mongo_collection/collection.rs
1use mongodb::Database;
2
3/// Trait for types that map to MongoDB collections.
4///
5/// This trait provides methods to get the collection name and obtain a typed
6/// MongoDB collection reference. It is typically derived using the `#[derive(Collection)]`
7/// macro rather than implemented manually.
8///
9/// # Examples
10///
11/// ```ignore
12/// use mongo_collection::Collection;
13/// use serde::{Serialize, Deserialize};
14///
15/// #[derive(Collection, Serialize, Deserialize, Debug, Clone)]
16/// struct User {
17/// username: String,
18/// }
19///
20/// // Get the collection name
21/// let name = User::name(); // "users"
22///
23/// // Get a typed MongoDB collection
24/// let users = User::collection(&db);
25/// ```
26pub trait Collection: Send + Sync + Sized {
27 /// Returns the name of the MongoDB collection for this type.
28 ///
29 /// When using the derive macro without specifying a custom name,
30 /// this returns the pluralized snake_case version of the struct name.
31 fn name() -> &'static str;
32
33 /// Returns a typed MongoDB collection reference for this type.
34 ///
35 /// # Arguments
36 ///
37 /// * `db` - A reference to the MongoDB database
38 ///
39 /// # Returns
40 ///
41 /// A `mongodb::Collection<Self>` that can be used for database operations.
42 ///
43 /// # Examples
44 ///
45 /// ```ignore
46 /// let users = User::collection(&db);
47 /// let user = users.find_one(doc! { "username": "alice" }).await?;
48 /// ```
49 fn collection(db: &Database) -> mongodb::Collection<Self> {
50 db.collection(Self::name())
51 }
52}