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
use mongodb::options::InsertOneOptions;

impl super::Database {
    pub fn insert_one<D, R>(
        &self,
        collection: &str,
        document: D,
        options: Option<InsertOneOptions>,
    ) -> Result<R, String>
    where
        D: serde::Serialize,
        for<'r> R: serde::Deserialize<'r>,
    {
        let collection = self.db.collection(&String::from(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, options) {
            Ok(inserted) => {
                let inserted_id: R = bson::from_bson(inserted.inserted_id).expect("");
                Ok(inserted_id)
            }
            Err(e) => Err(e.to_string()),
        }
    }
}