mongor/
util.rs

1// Authors: Robert Lopez
2// License: MIT (See `LICENSE.md`)
3
4use crate::error::Error;
5use mongodb::bson::{oid::ObjectId, Bson};
6
7/// Converts `Bson::ObjectId` to a `ObjectId`.
8///
9/// ---
10/// Example Usage:
11/// ```
12///
13/// let bson: Bson = Bson::ObjectId(...);
14///
15/// let oid: ObjectId = convert_bson_to_oid(bson)?;
16/// ```
17pub fn convert_bson_to_oid(bson: Bson) -> Result<ObjectId, Error> {
18    match bson.as_object_id() {
19        Some(oid) => Ok(oid),
20        None => Err(Error::internal(&format!(
21            "Could not convert Bson: {:?} to ObjectId",
22            bson
23        ))),
24    }
25}
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30
31    #[test]
32    fn test_convert_bson_to_oid() {
33        let oid_bson = Bson::ObjectId(ObjectId::new());
34
35        convert_bson_to_oid(oid_bson).unwrap();
36
37        let non_oid_bson = Bson::Int64(1337);
38
39        assert!(convert_bson_to_oid(non_oid_bson).is_err());
40    }
41}