2015-05-25 70 views
1

我想看看使用C++ 3.0驅動程序從MongoDB中檢索單個文檔的結果。 driver documentation描述了bsoncxx::document::value類的view() method(其由mongocxx::collection::find_one返回)。當我嘗試使用這樣的:無法調用bsoncxx :: document :: value :: view()

#include <bsoncxx/document/view.hpp> 
#include <bsoncxx/document/value.hpp> 
#include <mongocxx/instance> 
#include <mongocxx/client> 

mongocxx::instance inst{}; 
mongocxx::client conn{}; 
bsoncxx::document::view doc; 

auto db = conn["test"]; 

try { 
    auto docObj = db["collection"].find_one(document{} << 
     "field" << "value" << finalize); 
    doc = docObj.view(); 
} catch (mongocxx::exception::query e) { 
    std::cerr << "Couldn't retrieve document"; 
    return NULL; 
} 

... 

我得到以下編譯錯誤:

error: 'struct core::v1::optional<bsoncxx::v0::document::value>' has no member named 'view' 

在該行

doc = docObj.view(); 

我在做什麼錯?如果這不是使用find_one()的正確方式,我應該用什麼來代替?

回答

2

找到它。 bsoncxx ::可選模板意味着bsoncxx :: document :: value的成員可用作var-> member。上面的代碼應改爲:

doc = docObj->view(); 

這是混淆,因爲docObj是一個對象,而不是一個指針,而是呈現其底層對象,就好像是一個指針的對象。

-1

//對不起,我不能評論,但我不能在這種狀態下離開答案。

core::v1::optional<T>的行爲很像0​​。 和As(因爲C++ 17,std::optional或)在文檔中描述std::experimental::optional

When an object of type optional is contextually converted to bool , the conversion returns true if the object contains a value and false if it does not contain a value.

你必須檢查你的docObj通過應用運營商布爾它,因爲

The behavior [of operator*] is undefined if *this does not contain a value

包含的值

(這裏描述了一些bad_optional_access例外,但operator*的文檔說,嘗試訪問包含值時沒有值導致UB)

因此,您的代碼必須看起來像

if(docObj) { 
    doc docObj->view(); 
} else { 
    //Throw an exception? log an error to console? 
    //Do nothing? 
    std::cerr << "find_one() failed for" << std::endl << 
     bsoncxx::to_json(
       document{} << "field" << "value" << finalize 
      ) << std::endl; 
} 

這可能有助於如果find_one()由於某種原因失敗。

是的,core::v1::optional<T>std::optional的實現可能有所不同(至少我不能在official api documentation找到它)。 但最好檢查一下。

UPD:(?部分)file for stdx::optional所示,我是正確的:它可以使用std ::實驗::可選

+0

-1我不知道你想在這裏說什麼。請刪除您的關於無法評論的信息,並將其清除爲完整的答案,並解釋您正在嘗試解決的問題。就目前而言,我認爲你正試圖指出一個問題,它並不完全存在(由try catch塊處理)。 –

相關問題