mongor 0.1.10

Ergonomic MongoDB ODM
Documentation
// Authors: Robert Lopez
// License: MIT (See `LICENSE.md`)

use mongodb::Collection;
use serde::{Deserialize, Serialize};

pub mod all_impl;
pub mod by_field_value_impl;
pub mod by_oid_impl;
pub mod core_impl;
pub mod util_impl;

/// Represents a model to control a `Collection` of
/// document type `D`.
///
/// Implements methods found in the `core` module, alongside
/// extended versions for ease of use.
///
/// ---
/// Example Usage:
/// ```
/// let collection: Collection<D> = ...;
///
/// let mut model: Model<D> = Model::from(collection);
///
/// // Inserting
/// let mut documents: Vec<D> = vec![...];
///
/// let inserted_oids: Vec<ObjectId> = model.insert_many(documents, None, None).await?;
///
/// // Updating
/// let update_result: UpdateResult = model.update_one_by_oid(
///     &inserted_oids[0],
///     doc! { ... }
///     None,
///     None,
/// ).await?;
///
/// // Iterating over a cursor
/// let mut cursor = model.find_all(None, None).await?;
///
/// while let Some(document: D) = cursor.next().await? {
///     ...
/// }
///
/// // Iterating over a aggregation
/// let mut cursor = model.aggregate(
///     vec![
///         doc! { ... },
///         doc! { ... },
///         doc! { "$addField": ... },
///     ],
///     None,
///     None,
/// ).await?;
///
/// while let Some(generic_document: Document) = cursor.next_generic().await? {
///     ...
/// }
/// ```
#[derive(Debug)]
pub struct Model<D>
where
    D: Serialize + for<'a> Deserialize<'a> + Send + Sync + Unpin,
{
    pub collection: Collection<D>,
}

impl<D> Model<D>
where
    D: Serialize + for<'a> Deserialize<'a> + Send + Sync + Unpin,
{
    /// Constructs a Model from a `Collection` of documents.
    ///
    /// ---
    /// Example Usage:
    /// ```
    ///
    /// #[derive(Serialize, Deserialize)]
    /// pub struct Doc {
    ///     #[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
    ///     pub oid: Option<ObjectId>,
    ///     ...
    /// }
    ///
    /// let client: Client = ...;
    ///
    /// let collection: Collection<Doc> = client
    ///     .database("database_name")
    ///     .collection("collection_name");
    ///
    /// let model: Model<Doc> = Model::from(collection);
    /// ```
    pub fn from(collection: Collection<D>) -> Self {
        Self { collection }
    }
}