add unique + sort

This commit is contained in:
JMARyA 2024-08-28 08:45:44 +02:00
parent 228f113dbf
commit 05e09295a5
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263

View file

@ -250,6 +250,21 @@ pub trait Model:
}
}
/// Get unique values of a Models field
fn unique<T: DeserializeOwned>(
filter: mongodb::bson::Document,
field: &str,
) -> impl std::future::Future<Output = Vec<T>> {
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<Output = ()> + 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,
}