这是我迄今为止的尝试。我不明白如何告诉 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 `_`