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

标签 mongodb rust

我是 Rust 新手,并且是 MongoDB 的频繁用户。我通常使用node.js + Mongoose ODM .

RUST 中是否有任何 MongoDB ODM 可以像 Mongoose ODM 一样实现自定义模式和业务逻辑 Hook ?或者我需要自己在 Rust 的类型系统中实现它?

这是 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

据我所知.. mongodm-rs不这样做 也不Wither也不Avocado

最佳答案

您可能不需要 ODM。与serde (所有这些 ODM 都使用它),“模式”是在结构本身上实现的,因此您可以使用 impl block 添加所需的任何方法。它看起来像这样:

    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();

这个结构可以存储在 MongoDB 中(因为它派生出序列化和反序列化) - 要了解如何存储,请查看我的博客文章 Up and Running with Rust and MongoDB 。我的同事 Isabelle's post 有一些关于如何将 serde 与 MongoDB 结合使用的更多最新详细信息。 .

关于mongodb - 如何在 Rust 中实现 MongoDB 模式和业务逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66648482/

相关文章:

MongoDB 索引用于查找和排序

mongodb - 环境变量 MONGODB_CONFIG_OVERRIDE_NOFORK == 1,覆盖\"processManagement.fork\"为 false”

function - 从 select crate 返回 document::find 的结果时如何分配生命周期?

rust - 创建Docker镜像后出现的问题

rust - 迭代递归结构时无法获取可变引用 : cannot borrow as mutable more than once at a time

javascript - 如何删除 Mongoose 文档并从另一个模型引用它?

javascript - 为什么当使用 Node Express 和 Backbone 获取请求时,我会得到用户集合和额外的对象?

mongodb - 返回子文档数组与用户定义数组的交集?

rust - 理解 &type + 'a 语法

regex - 如何编写两个对 Regex::replace_all 的调用?