我是 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/