mongor 0.1.10

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

use crate::error::Error;
use mongodb::{bson::Document, options::FindOneAndReplaceOptions, ClientSession, Collection};
use serde::{Deserialize, Serialize};

/// Executes a `findOneAndReplace` query on `Collection`,
/// returns the original document by default.
///
/// https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndReplace/
///
/// ---
/// Example Usage:
/// ```
///
/// let collection: Collection<D> = ...;
///
/// let replacement: D = ...;
///
/// let original_document: D = find_one_and_replace(
///     &collection,
///     doc! { ... },
///     replacement,
///     None::<FindOneAndReplaceOptions>,
///     None::<&mut ClientSession>,
/// ).await?;
/// ```
pub async fn find_one_and_replace<D>(
    collection: &Collection<D>,
    query: Document,
    replacement: D,
    options: Option<FindOneAndReplaceOptions>,
    session: Option<&mut ClientSession>,
) -> Result<Option<D>, Error>
where
    D: Serialize + for<'a> Deserialize<'a> + Send + Sync,
{
    let result = if let Some(session) = session {
        collection
            .find_one_and_replace(query, replacement)
            .with_options(options)
            .session(session)
            .await
    } else {
        collection
            .find_one_and_replace(query, replacement)
            .with_options(options)
            .await
    }
    .map_err(Error::Mongo)?;

    Ok(result)
}