我正在尝试从MongoDB查询中检索的BSON .get
上使用OrderedDocument
方法。为了处理查询中的任何错误,我在查询上使用了match
运算符。
let id: String = "example".to_string();
let doc = match db.media.find_one(
Some(doc! {
"id" : id
}),
None,
) {
Ok(c) => c,
Err(e) => {
// do stuff with the error
return;
}
};
println!("{:?}", doc.get("field"));
这将为最后一行返回错误:
错误[E0599]:在当前范围内找不到类型为
get
的名为std::option::Option<bson::ordered::OrderedDocument>
的方法
这必须表示从match
操作返回的类型是Option
,而不是我所期望的OrderedDocument
。为什么在上例中返回类型为{{1}的c
变量而不是查询的BSON文档类型?如何从Option
返回所需的类型?还是这是错误的解决方法?
答案 0 :(得分:3)
从match
操作返回的类型就是您输入的内容。在这种情况下,类型为c
。
find_one
返回一个Result<Option<Document>>
。由于您的模式仅在Result
部分匹配,因此您将获得内部Option
。一种解决方案是使用一些更精确的模式:
let doc = match db.media.find_one(Some(doc! { "id": id }), None) {
Ok(Some(c)) => c,
Ok(None) => {
println!("Nothing found");
return;
}
Err(e) => {
println!("An error occurred: {:?}", e);
return;
}
};