Skip to main content

CollectionRepository

Derive Macro CollectionRepository 

Source
#[derive(CollectionRepository)]
Expand description

Automatically derives the CollectionRepository trait implementation

This macro automatically implements the CollectionRepository trait for a struct that already implements the Collection trait. The struct must also implement Clone, Send, Sync, Unpin, Serialize, and Deserialize.

§Usage

ⓘ
use mongo_collection::{Collection, CollectionRepository};
use serde::{Serialize, Deserialize};

#[derive(Collection, CollectionRepository, Serialize, Deserialize, Debug, Clone)]
struct User {
    #[serde(rename = "_id")]
    id: String,
    name: String,
    email: String,
}

// Now you can use all CRUD operations:
// User::create(&db, &user).await?;
// User::find_by_id(&db, "123").await?;
// User::find_paginated(&db, doc!{}, &query).await?;

§Requirements

The struct must derive or implement:

  • Collection - Provides collection name and reference
  • Clone - Required for return values
  • Serialize - For MongoDB serialization
  • Deserialize - For MongoDB deserialization

§Example with all derives

ⓘ
#[derive(Collection, CollectionRepository, Serialize, Deserialize, Debug, Clone)]
#[collection(name = "users")]
struct User {
    #[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
    id: Option<String>,
    name: String,
    email: String,
}