[−][src]Crate mongodm
MongODM
A thin ODM layer for MongoDB built upon the official Rust driver.
Main features:
- A stronger API leveraging Rust type system
- Data structure models are defined using the well-known
serde
serialization framework - Index support on top of the
Database::run_command
(index management is currently not implemented in the underlying driver) - Indexes synchronization
- Additional compile-time checks for queries using macros and type associated to mongo operators (eg:
And
instead of "$and")
Example
ⓘThis example is not tested
use mongodm::{ToRepository, Model, Indexes, Index, IndexOption}; use mongodm::mongo::{Client, options::ClientOptions, bson::doc}; use serde::{Serialize, Deserialize}; use std::borrow::Cow; #[derive(Serialize, Deserialize, Debug, PartialEq)] struct User { username: String, last_seen: i64, } impl Model for User { fn coll_name() -> &'static str { "user" } fn indexes() -> Indexes { Indexes::new().with(Index::new("username").with_option(IndexOption::Unique)) } } let client_options = ClientOptions::parse("mongodb://localhost:27017").await?; let client = Client::with_options(client_options)?; let db = client.database("mongodm_wayk_demo"); let repository = db.repository::<User>(); repository.sync_indexes().await?; // indexes are now synced in backend let user = User { username: String::from("David"), last_seen: 1000, }; repository.insert_one(&user, None).await?; // field! is used to make sure at compile time that `username` is a field of `User` use mongodm::field; let fetched_user = repository.find_one(doc! { field!(username in User): "David" }, None).await?; assert!(fetched_user.is_some()); assert_eq!(fetched_user.unwrap(), user); // f! is a shorter version of field! use mongodm::f; repository.find_one(doc! { f!(username in User): "David" }, None).await?.unwrap(); // With static operators for queries (prevent invalid queries due to typos) use mongodm::operator::*; repository.find_one( doc! { And: [ { f!(username in User): "David" }, { f!(last_seen in User): { GreaterThan: 500 } }, ] }, None ).await?.unwrap();
Re-exports
pub use cursor::ModelCursor; |
pub use index::Index; |
pub use index::IndexOption; |
pub use index::Indexes; |
pub use repository::Repository; |
pub use mongodb as mongo; |
Modules
cursor |
|
index | Indexes are used for efficient mongo queries. |
operator | Static operators for queries to prevent invalid queries due to typos. |
repository | Repositories are abstraction over a specific mongo collection for a given |
Macros
f | Shorthand for |
field | Statically check presence of field in a given type and stringify it. |
Traits
Model | Define collection configuration and associated indexes. |
ToRepository | Utilities methods to get a |