mongor 0.1.10

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

use crate::{error::Error, util::convert_bson_to_oid};
use mongodb::{bson::oid::ObjectId, options::*, ClientSession, Collection};
use serde::{Deserialize, Serialize};

/// Executes a `insertOne` query on a `Collection`.
///
/// https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne/
///
/// ---
/// Example Usage:
/// ```
///
/// let collection: Collection<D> = ...;
///
/// let document: D = ...;
///
/// let inserted_oid: ObjectId = insert_one(
///     &collection,
///     document,
///     None::<InsertOneOptions>,
///     None::<&mut ClientSession>,
/// ).await?;
/// ```
pub async fn insert_one<D>(
    collection: &Collection<D>,
    document: D,
    options: Option<InsertOneOptions>,
    session: Option<&mut ClientSession>,
) -> Result<ObjectId, Error>
where
    D: Serialize + for<'a> Deserialize<'a> + Send + Sync,
{
    let insert_one_result = if let Some(session) = session {
        collection
            .insert_one(document)
            .with_options(options)
            .session(session)
            .await
    } else {
        collection.insert_one(document).with_options(options).await
    }
    .map_err(Error::Mongo)?;

    convert_bson_to_oid(insert_one_result.inserted_id)
}

/// Executes a `insertMany` query on a `Collection`.
///
/// https://www.mongodb.com/docs/manual/reference/method/db.collection.insertMany/
///
/// ---
/// Example Usage:
/// ```
///
/// let collection: Collection<D> = ...;
///
/// let documents: Vec<D> = ...;
///
/// let inserted_oids: Vec<ObjectId> = insert_many(
///     &collection,
///     documents,
///     None::<InsertManyOptions>,
///     None::<&mut ClientSession>,
/// ).await?;
/// ```
pub async fn insert_many<D>(
    collection: &Collection<D>,
    documents: Vec<D>,
    options: Option<InsertManyOptions>,
    session: Option<&mut ClientSession>,
) -> Result<Vec<ObjectId>, Error>
where
    D: Serialize + for<'a> Deserialize<'a> + Send + Sync,
{
    let insert_many_result = if let Some(session) = session {
        collection
            .insert_many(documents)
            .with_options(options)
            .session(session)
            .await
    } else {
        collection
            .insert_many(documents)
            .with_options(options)
            .await
    }
    .map_err(Error::Mongo)?;

    let mut inserted_ids = vec![];

    for (_, bson) in insert_many_result.inserted_ids {
        inserted_ids.push(convert_bson_to_oid(bson)?);
    }

    Ok(inserted_ids)
}