mongoose

Crates.iomongoose
lib.rsmongoose
version0.6.2
sourcesrc
created_at2023-01-30 04:53:37.449239
updated_at2024-07-23 18:28:35.279166
descriptionConvenient MongoDb Wrappers
homepagehttps://github.com/judegiordano/mongoose-rs
repositoryhttps://github.com/judegiordano/mongoose-rs
max_upload_size
id771456
size46,431
Jude Giordano (judegiordano)

documentation

https://github.com/judegiordano/mongoose-rs

README

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,
        }
    }
}
Commit count: 64

cargo fmt