1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use mongodb::db::ThreadedDatabase;
use mongodb::common::WriteConcern;

impl super::Database {
    pub fn insert_one<D, R>(
        &self,
        collection: String,
        document: D,
        write_concern: Option<WriteConcern>,
    ) -> Result<R, String>
        where
            D: serde::Serialize + std::fmt::Debug,
            for<'r> R: serde::Deserialize<'r>,
    {
        let collection = self.db.get().unwrap().collection(&collection);

        let entry_bson = match bson::to_bson(&document)
            .expect("cannot parse_into_bson") {
            bson::Bson::Document(doc) => doc,
            _ => return Err("cannot parse_into_bson".to_string())
        };

        match collection.insert_one(
            entry_bson,
            write_concern,
        ) {
            Ok(inserted) => {
                let inserted_id: R = match bson::from_bson(match inserted.inserted_id {
                    Some(id) => id,
                    _ => return Err("cannot_retreive_inserted_id".to_string())
                }) {
                    Ok(from_bson) => from_bson,
                    Err(e) => return Err(e.to_string())
                };
                Ok(inserted_id)
            }
            Err(e) => Err(e.to_string())
        }
    }
}