尝试使用r2d2-mongodb和actix_web将传入数据存储到mongo中。
#[derive(Serialize, Deserialize, Debug)]
struct Weight {
desc: String,
grams: u32,
}
fn store_weights(weights: web::Json<Vec<Weight>>, db: web::Data<Pool<MongodbConnectionManager>>) -> Result<String> {
let conn = db.get().unwrap();
let coll = conn.collection("weights");
for weight in weights.iter() {
coll.insert_one(weight.into(), None).unwrap();
}
Ok(String::from("ok"))
}
我似乎无法理解将重量转换为insert_one
所需的方式。上面的代码错误进入error[E0277]: the trait bound 'bson::ordered::OrderedDocument: std::convert::From<&api::weight::Weight>' is not satisfied
insert_one
[pub fn insert_one(
&self,
doc: Document,
options: impl Into<Option<InsertOneOptions>>
) -> Result<InsertOneResult>
是Document
,是bson::Document
的别名。
您的类型bson::ordered::OrderedDocument
没有实现bson::ordered::OrderedDocument
必需的特征Weight
。您可以实现它,但是更惯用的方式是将Into<Document>
特性与weight::into()
结合使用:
Serialize
注意:
[bson::to_bson
返回一个枚举fn store_weights(weights: Vec<Weight>) -> Result<&'static str, Box<dyn std::error::Error>> {
let conn = db.get()?;
let coll = conn.collection("weights");
for weight in weights.iter() {
let document = match bson::to_bson(weight)? {
Document(doc) => doc,
_ => unreachable!(), // Weight should always serialize to a document
};
coll.insert_one(document, None)?;
}
Ok("ok")
}
,可以是to_bson
,Bson
,Bson
等。我们使用Array
来确保它是Boolean
。
我使用Document
而不是拆开来利用match
返回类型。确保Document
类型的错误为?
。
返回Result
而不是为每个请求分配新的Into<Error>
。