[][src]Crate wither


Build Status Crates.io docs.rs License Crates.io Crates.io GitHub issues open GitHub issues closed

An ODM for MongoDB built upon the mongo rust driver. Please ⭐ on github!

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.2, 3.4, 3.6 & 4.0.

items of interest

getting started

To get started, simply derive Model on your struct along with a few other serde derivations. Let's step through a full example with imports and all.

// First, we add import statements for the crates that we need.
// In Rust 2018, `extern crate` declarations will no longer be needed.
extern crate mongodb;
extern crate serde;
#[macro_use(Serialize, Deserialize)]
extern crate serde_derive;
extern crate wither;
extern crate wither_derive;

// Next we bring a few types into scope for our example.
use mongodb::{
    Client, ThreadedClient,
    db::{Database, ThreadedDatabase},
use wither::prelude::*;

// Now we define our model. Simple as deriving a few traits.
#[derive(Model, Serialize, Deserialize)]
struct User {
    /// The ID of the model.
    #[serde(rename="_id", skip_serializing_if="Option::is_none")]
    pub id: Option<ObjectId>,

    /// This field has a unique index on it.
    #[model(index(index="dsc", unique="true"))]
    pub email: String,

fn main() {
    // Create a user.
    let db = mongodb::Client::with_uri("mongodb://localhost:27017/").unwrap().db("mydb");
    let mut me = User{id: None, email: "my.email@example.com".to_string()};
    me.save(db.clone(), None);

    // Update user's email address.
    me.update(db.clone(), None, doc!{"$set": doc!{"email": "new.email@example.com"}}, None).unwrap();

    // Fetch all users.
    let all_users = User::find(db.clone(), None, None).unwrap();

next steps

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:

  • deriving model - learn more about automatically deriving the Model trait on your structs.
  • model usage - check out some of the other methods available to you from your models.
  • syncing indexes - learn how to synchronize a model's indexes with the database.
  • logging - learn how to hook into this crate's logging mechanisms (hint, we use Rust's standard logging facade).
  • migrations - learn about defining migrations to be run against your model's collection.

Good luck on the path.


pub extern crate mongodb;
pub use migration::IntervalMigration;
pub use migration::Migration;
pub use model::basic_index_options;
pub use model::Model;



Interface for schema migrations.


Model related code.


All traits needed for basic usage of the wither system.