mongor 0.1.10

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

use crate::error::Error;
use mongodb::bson::{oid::ObjectId, Bson};

/// Converts `Bson::ObjectId` to a `ObjectId`.
///
/// ---
/// Example Usage:
/// ```
///
/// let bson: Bson = Bson::ObjectId(...);
///
/// let oid: ObjectId = convert_bson_to_oid(bson)?;
/// ```
pub fn convert_bson_to_oid(bson: Bson) -> Result<ObjectId, Error> {
    match bson.as_object_id() {
        Some(oid) => Ok(oid),
        None => Err(Error::internal(&format!(
            "Could not convert Bson: {:?} to ObjectId",
            bson
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_convert_bson_to_oid() {
        let oid_bson = Bson::ObjectId(ObjectId::new());

        convert_bson_to_oid(oid_bson).unwrap();

        let non_oid_bson = Bson::Int64(1337);

        assert!(convert_bson_to_oid(non_oid_bson).is_err());
    }
}