我是 Rust 新手,也是 MongoDB 的频繁用户。我通常使用node.js+ Mongoose ODM。
RUST 中是否有任何 MongoDB ODM 可以像 Mongoose ODM 一样实现自定义模式和业务逻辑挂钩?或者我需要自己在 Rust 的类型系统中实现它?
这是猫鼬的一个例子
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
Run Code Online (Sandbox Code Playgroud)
据我所知.. mongodm-rs不会这样做,Wither和Avocado也不会这样做
您可能不需要 ODM。使用serde(所有这些 ODM 都使用它),“模式”是在结构本身上实现的,因此您可以使用块添加任何您想要的方法impl。它看起来像这样:
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();
Run Code Online (Sandbox Code Playgroud)
该结构可以存储在 MongoDB 中(因为它派生了 Serialize 和 Deserialize) - 要了解如何存储,请查看我的博客文章Up and Running with Rust and MongoDB。在我的同事Isabelle 的帖子中,有一些关于如何将 serde 与 MongoDB 结合使用的更多最新详细信息。
| 归档时间: |
|
| 查看次数: |
579 次 |
| 最近记录: |