[英]Save Nested Struct with Rust mongodb returns error the trait `From<T>` is not implemented for `Bson`
I have a struct to model an Item.我有一个 model 一个项目的结构。 But some of its field depends of other struct.但它的一些领域依赖于其他结构。 And I want to save this nested object into mongodb with MongoDB Rust Driver.我想用 MongoDB ZF5E265D607CB720058FC166E0008 驱动程序将这个嵌套的 object 保存到 mongodb 中。 ( https://github.com/mongodb/mongo-rust-driver ) ( https://github.com/mongodb/mongo-rust-driver )
use mongodb::bson::doc;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct CustomUnit {
pub unit: String,
pub multiplier: f64,
}
// Item depends on CustomUnit struct above. Nested object, JSON-like
struct Item {
pub name: String,
pub qty: f64,
pub unit: CustomUnit ,
}
// declare an item and an unit
let my_unit = CustomUnit {unit: "BOX".to_string(), multiplier: 12.0};
let a = Item {name: "FOO Item".to_string(), qty: 10.0, unit: my_unit};
// later in the code I extracted the value for each field
let name = a.name.clone();
let qty = a.qty;
let unit = a.unit;
let doc = doc! {
"name": name.clone(),
"qty": qty,
"unit": unit,
};
// throws an error: "the trait `From<CustomUnit>` is not implemented for `Bson`"
db.collection(COLL).insert_one(doc, None).await
this displays an error message:这将显示一条错误消息:
_^ the trait `From<CustomUnit>` is not implemented for `Bson`
= help: the following implementations were found:
<Bson as From<&T>>
<Bson as From<&[T]>>
<Bson as From<&str>>
<Bson as From<Regex>>
and 19 others
= note: required by `std::convert::From::from`
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
How to implement this From<CustomUnit>
for Bson
trait?如何为Bson
特征实现这个From<CustomUnit>
?
impl From<CustomUnit> for Bson {
fn from(unit: CustomUnit) -> Self {
// what to do here ? and how to return a Bson document ?
// there's no explanation in rust-mongodb manual
}
}
Since doc!
自从doc!
internally converts each field into Binary JSON (BSON).在内部将每个字段转换为二进制 JSON (BSON)。 doc!
converts known types into BSON automatically, but since unit is a user made struct, it doesn't know how to.自动将已知类型转换为 BSON,但由于 unit 是用户制作的结构,它不知道如何去做。
use mongodb::bson;
#[derive(Serialize, Deserialize, Debug)]
struct CustomUnit {
pub unit: String,
pub multiplier: f64,
}
let doc = doc! {
"name": name.clone(),
"qty": qty,
"unit": bson::to_bson(&unit).unwrap(),
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.