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
use bson::Document;
use mongodb::options::FindOneAndUpdateOptions;

impl super::Database {
    pub fn find_one_and_update<R>(
        &self,
        collection: &str,
        filter: Document,
        update: Document,
        options: Option<FindOneAndUpdateOptions>,
    ) -> Result<R, String>
    where
        for<'r> R: serde::Deserialize<'r>,
    {
        let collection = self.db.collection(&String::from(collection));
        match match collection.find_one_and_update(filter, update, options) {
            Ok(doc) => doc,
            Err(e) => return Err(e.to_string()),
        } {
            Some(updated_doc) => {
                let data: R = match bson::from_bson(bson::Bson::Document(updated_doc)) {
                    Ok(from_bson) => from_bson,
                    Err(e) => return Err(e.to_string()),
                };
                Ok(data)
            }
            _ => return Err("cannot_find_document".to_string()),
        }
    }
}