From 05e09295a5cb121d35e19a437daa51b147567872 Mon Sep 17 00:00:00 2001 From: JMARyA Date: Wed, 28 Aug 2024 08:45:44 +0200 Subject: [PATCH] add unique + sort --- src/model/mod.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/model/mod.rs b/src/model/mod.rs index 0ceff52..7279058 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -250,6 +250,21 @@ pub trait Model: } } + /// Get unique values of a Models field + fn unique( + filter: mongodb::bson::Document, + field: &str, + ) -> impl std::future::Future> { + async move { + let db = get_mongo!(); + let collection = col!(db, Self::collection_name()); + let res = collection.distinct(field, filter, None).await.unwrap(); + res.into_iter() + .filter_map(|x| mongodb::bson::from_bson(x).ok()) + .collect() + } + } + /// Get multiple partial `Model`s by using a filter from the database. Pass a `limit` parameter to limit the amount of `Model`s returned. #[must_use] fn find_partial( @@ -330,3 +345,20 @@ pub trait Model: update: &mut mongodb::bson::Document, ) -> impl std::future::Future + Send; } + +/// Sorting Order +/// +/// # Example +/// ```ignore +/// let m = MyModel::find(doc! {}, None, Some(doc! { +/// "sort_key": Sort::Ascending +/// })).await.unwrap(); +/// ``` +#[repr(i8)] +#[derive(serde::Serialize, serde::Deserialize, Debug)] +pub enum Sort { + /// Sort in ascending order + Ascending = 1, + /// Sort in descending order + Descending = -1, +}