I'm new to Rust and a frequent user of MongoDB. I usually use node.js + Mongoose ODM.
Is there any MongoDB ODM in RUST that implements a custom schema and business logic hooks like Mongoose ODM ? Or do I need to implement it myself inside the Rust's type system?
This is an example from Mongoose
const schema = kittySchema = new Schema(..);
// they implement the 'meow' method in the Kitty Schema
schema.method('meow', function () {
console.log('meeeeeoooooooooooow');
})
// so anytime a Kitty schema instance is created
const Kitty = mongoose.model('Kitty', schema);
const fizz = new Kitty;
// fizz as the instance of Kitty Schema automatically has meow() method
fizz.meow(); // outputs: meeeeeooooooooooooow
As far as I know.. mongodm-rs doesn't do that nor Wither nor Avocado
You may not need an ODM. With serde (which is used by all those ODMs), the "schema" is implemented on the struct itself, so you can add any methods you want with an impl block. It would look something like this:
use serde::{Deserialize, Serialize};
// Deriving from serde's Serialize and Deserialize, meaning this struct can be converted to and from BSON for storage and retrieval in MongoDB:
#[derive(Serialize, Deserialize, Debug)]
struct Kitty {
name: String,
}
impl Kitty {
fn meow(&self) {
println!("{} says 'meeeeeoooooooooooow'", &self.name);
}
}
let fizz = Kitty {
name: String::from("Fizz"),
};
fizz.meow();
This struct can be stored in MongoDB (because it derives Serialize and Deserialize) - to see how, check out my blog post Up and Running with Rust and MongoDB. There's some more up-to-date details about how to use serde with MongoDB in my colleague Isabelle's post.