mongor 0.1.10

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

use super::Model;
use crate::error::Error;
use mongodb::{bson::Document, options::*, ClientSession};
use serde::{Deserialize, Serialize};

impl<D> Model<D>
where
    D: Serialize + for<'a> Deserialize<'a> + Send + Sync + Unpin,
{
    /// Returns if a document exists by a filter in `self.collection`.
    ///
    /// ---
    /// Example Usage:
    /// ```
    ///
    /// let model: Model<D> = ...;
    ///
    /// if model.exists(
    ///     doc! { "user": "admin" },
    ///     None::<FindOneOptions>,
    ///     None::<&mut ClientSession>,
    /// ).await? {
    ///     ...
    /// }
    /// ```
    pub async fn exists(
        &self,
        filter: Document,
        options: Option<FindOneOptions>,
        session: Option<&mut ClientSession>,
    ) -> Result<bool, Error> {
        Ok(self.find_one(filter, options, session).await?.is_some())
    }

    /// Returns the document count for `self.collection` by a given filter.
    ///
    /// ---
    /// Example Usage:
    /// ```
    ///
    /// let model: Model<D> = ...;
    ///
    /// let total_documents: usize = model.count_documents(
    ///     doc! { ... },
    ///     None::<CountOptions>,
    ///     None::<&mut ClientSession>,
    /// ).await?;
    /// ```
    pub async fn count_documents(
        &self,
        filter: Document,
        options: Option<CountOptions>,
        session: Option<&mut ClientSession>,
    ) -> Result<usize, Error> {
        if let Some(session) = session {
            self.collection
                .count_documents(filter)
                .with_options(options)
                .session(session)
                .await
                .map(|count| count as usize)
                .map_err(Error::Mongo)
        } else {
            self.collection
                .count_documents(filter)
                .with_options(options)
                .await
                .map(|count| count as usize)
                .map_err(Error::Mongo)
        }
    }
}