21 releases (5 breaking)

0.6.2 Jul 23, 2024
0.4.0 Feb 28, 2024
0.1.16 Apr 23, 2023
0.1.14 Mar 28, 2023

#537 in Database interfaces

Download history 1/week @ 2024-06-27 11/week @ 2024-07-04 94/week @ 2024-07-18 33/week @ 2024-07-25 3/week @ 2024-08-01 8/week @ 2024-08-08 2/week @ 2024-08-15 13/week @ 2024-09-12 59/week @ 2024-09-19 14/week @ 2024-09-26 2/week @ 2024-10-03

88 downloads per month

MIT license

43KB
1K SLoC

Mongoose

use async_trait::async_trait;
use bson::doc;
use chrono::{DateTime, Utc};
use mongodb::{options::IndexOptions, Database, IndexModel};
use serde::{Deserialize, Serialize};
use mongoose::Model;

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct User {
    #[serde(rename = "_id")]
    pub id: String,
    pub age: u32,
    pub username: String,
    #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
    pub created_at: DateTime<Utc>,
    #[serde(with = "bson::serde_helpers::chrono_datetime_as_bson_datetime")]
    pub updated_at: DateTime<Utc>,
}

#[async_trait]
impl Model for User {
    async fn create_indexes(db: &Database) {
        let username_index = IndexModel::builder()
            .keys(doc! { "username": 1 })
            .options(IndexOptions::builder().unique(true).build())
            .build();
        let indexes = [username_index];
        if let Err(err) = db
            .collection::<Self>(Self::collection_name())
            .create_indexes(indexes, None)
            .await
        {
            tracing::error!(
                "error creating {:?} indexes: {:?}",
                Self::collection_name(),
                err
            );
        }
        tracing::debug!("indexes created for {:?}", Self::collection_name());
    }
}

impl Default for User {
    fn default() -> Self {
        let now = chrono::Utc::now();
        Self {
            id: Self::generate_id(),
            age: u32::default(),
            username: String::new(),
            created_at: now,
            updated_at: now,
        }
    }
}

Dependencies

~25–36MB
~662K SLoC