Spark-ORM: MongoDB ORM for Rust
Spark-ORM is a high-performance, open-source Object-Relational Mapping (ORM) library designed specifically for MongoDB in Rust. It seamlessly bridges Rust structs with MongoDB collections, effortlessly converting structs into models.
Features
-
Derive Models: Effortlessly convert Rust structs into MongoDB models using the
Modeltrait derivation. -
Custom Collection Names: Tailor collection names for your models with the
#[coll_name]attribute. -
Memory Efficiency: Built for speed and memory efficiency, Spark-ORM offers a non-heap copy ORM solution for MongoDB.
Getting Started
-
Define your model by simply applying the
Modelattribute and setting the collection name withcoll_name: -
Connect to the database in one of two ways:
a. Establish a global connection:
global_connect.await;b. Or connect locally:
connect.await;For the global connection, Spark retains it throughout the program, accessible via:
Spark::get_db();
Usage
Instantiate the model:
let mut user = new_model;
OR you can use the global connection :
let mut user = new_model;
if you didn't set global connection , the new_model function will panic
Update attributes:
user.name = "Hossein".to_string;
user.age = 22;
Save to the database:
user.save.await.unwrap;
Find a model:
let mut user_model = new_model;
let mut sample = default ;
sample.name = "Hossein".to_string;
let founded = user_model.find_one.await.unwrap;
println!;
Update and save:
let mut user = new_model;
user.name = "Hossein".to_string;
user.email = "spark_orm_test".to_string;
user.save.await;
user.name = "Nothing".to_string;
user.save.await;
or
let db = get_db.await;
let user_model = new_model;
let updated = user_model.update.await.unwrap;
println!;
Delete a record:
let mut user = new_model;
user.delete.await;
Note: you can use the ? instead of unwrap
Model
The model trait adds _id , timestamps (created_at , updated_at , deleted_at) to your struct and fill automatically
Attributes
Define index or unique attributes for struct fields:
These indexes are registered during the first initiation of Product.