如何将actix_web Json存储到mongodb?

问题描述 投票:0回答:1

尝试使用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

mongodb rust actix-web
1个回答
0
投票

signature for insert_one是:

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

注意:

  1. [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_bsonBsonBson等。我们使用Array来确保它是Boolean

  2. 我使用Document而不是拆开来利用match返回类型。确保Document类型的错误为?

  3. 返回Result而不是为每个请求分配新的Into<Error>

© www.soinside.com 2019 - 2024. All rights reserved.