如何在 Rust 中实现 MongoDB 模式和业务逻辑?

Den*_*Hiu 2 mongodb rust

我是 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不会这样做,WitherAvocado也不会这样做

Jud*_*y2K 5

您可能不需要 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 结合使用的更多最新详细信息。