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
41
42
43
use bson::Bson;
use mongodb::options::InsertManyOptions;
use std::collections::HashMap;

impl super::Database {
    pub fn insert_many<D, R>(
        &self,
        collection: &str,
        list_document: Vec<D>,
        options: Option<InsertManyOptions>,
    ) -> Result<Vec<R>, String>
    where
        D: serde::Serialize,
        for<'r> R: serde::Deserialize<'r>,
    {
        let collection = self.db.collection(&String::from(collection));

        let mut list_entry_bson = vec![];

        for doc in list_document {
            list_entry_bson.push(match bson::to_bson(&doc).expect("cannot parse_into_bson") {
                bson::Bson::Document(doc) => doc,
                _ => panic!("cannot_parse_to_document"),
            })
        }

        match collection.insert_many(list_entry_bson, options) {
            Ok(inserted_id_list) => {
                let list_ids: HashMap<usize, Bson> = inserted_id_list.inserted_ids;

                let list_ids_iter: Vec<Bson> = list_ids.values().cloned().collect();

                let inserted_id_result: Vec<R> = list_ids_iter
                    .iter()
                    .filter_map(|inserted_id| bson::from_bson(inserted_id.clone()).expect(""))
                    .collect();

                Ok(inserted_id_result)
            }
            Err(e) => Err(e.to_string()),
        }
    }
}