如何将MongoDB中的文档反序列化为Rust结构?

时间:2018-06-27 13:03:20

标签: mongodb rust serde

到目前为止,这是我的尝试。我不明白如何告诉Rust将MongoDB结果反序列化为结构。

我已经定义了一个我想将数据映射到的名为Thing的结构。

#[macro_use(bson, doc)]
extern crate bson;
extern crate mongodb;
#[macro_use]
extern crate serde_derive;

use mongodb::db::ThreadedDatabase;
use mongodb::{Client, ThreadedClient};

fn main() {
    let client =
        Client::connect("localhost", 27017).expect("Failed to initialize standalone client.");

    let coll = client.db("bestestDB").collection("things");

    let doc = doc! {
        "$text": { "$search": "Love" },
    };

    #[derive(Serialize, Deserialize, Debug)]
    pub struct Thing {
        #[serde(rename = "_id")] // Use MongoDB's special primary key field name when serializing
        pub id: String,
        pub name: String,
        pub image: String,
    }

    let mut cursor = coll
        .find(Some(doc.clone()), None)
        .ok()
        .expect("Failed to execute find.");

    let item = cursor.next();

    // cursor.next() returns an Option<Result<Document>>
    match item {
        Some(Ok(doc)) => match bson::from_bson(bson::Bson::Document(doc)) {
            Ok(thing) => println!("{:?}", thing),
            Err(_) => panic!("Deserializing failed!"),
        },
        Some(Err(_)) => panic!("Failed to get next from server!"),
        None => panic!("Server returned no results!"),
    }
}

然后我收到以下错误消息:

   |
37 | Ok(thing) => println!("{:?}", thing),
   |    ^^^^^ cannot infer type for `_`

0 个答案:

没有答案