Crates.io | wither |
lib.rs | wither |
version | 0.9.0 |
source | src |
created_at | 2017-08-18 16:36:13.607451 |
updated_at | 2021-02-17 19:01:36.542149 |
description | An ODM for MongoDB built upon the mongo rust driver. |
homepage | https://github.com/thedodd/wither |
repository | https://github.com/thedodd/wither |
max_upload_size | |
id | 28033 |
size | 149,374 |
The primary goal of this project is to provide a simple, sane & predictable interface into MongoDB based on data models. If at any point this system might get in your way, you have direct access to the underlying driver. This project is tested against MongoDB 3.6
, 4.0
, 4.2
& 4.4
.
GREAT NEWS! Wither is now based on the official MongoDB Rust driver. Thanks to advancements in the driver, Wither is now fully asynchronous. Simply mirroring the features of the underlying MongoDB driver, Wither supports the following runtimes:
tokio-runtime
(default) activates the tokio runtime.async-std-runtime
activates the async-std runtime.Due to updates in the underlying driver, there is a fair number of breaking changes in the Model
trait, as well as the Model
derive macro. Details can be found in the changelog and the documentation. Furthermore, everything is now async by default, and the synchronous interface has been completely removed from the repo.
To get started, simply derive Model
on your struct along with a few other serde derivations. Let's step through a full example.
use futures::stream::StreamExt;
use serde::{Serialize, Deserialize};
use wither::{prelude::*, Result};
use wither::bson::{doc, oid::ObjectId};
use wither::mongodb::Client;
// Define a model. Simple as deriving a few traits.
#[derive(Debug, Model, Serialize, Deserialize)]
#[model(index(keys=r#"doc!{"email": 1}"#, options=r#"doc!{"unique": true}"#))]
struct User {
/// The ID of the model.
#[serde(rename="_id", skip_serializing_if="Option::is_none")]
pub id: Option<ObjectId>,
/// The user's email address.
pub email: String,
}
#[tokio::main]
async fn main() -> Result<()> {
// Connect & sync indexes.
let db = Client::with_uri_str("mongodb://localhost:27017/").await?.database("mydb");
User::sync(&db).await?;
// Create a user.
let mut me = User{id: None, email: String::from("my.email@example.com")};
me.save(&db, None).await?;
// Update user's email address.
me.update(&db, None, doc!{"$set": doc!{"email": "new.email@example.com"}}, None).await?;
// Fetch all users.
let mut cursor = User::find(&db, None, None).await?;
while let Some(user) = cursor.next().await {
println!("{:?}", user);
}
Ok(())
}
And that's all there is to it. Now you are ready to tackle some of the other important parts of the model lifecycle. Some additional items to look into:
Model
trait on your structs.Good luck on the path.