一个基于REACT-CPP的库,使用C++编写的异步mongo访问库。通过使用lambda表达式和回调函数的形式来返回查询结果。
这个库的工作原理与普通的mongoC++库基本相同,只是所有函数接受一个lambda参数,当结果可用(或失败)时将调用该参数。
示例代码
React::Mongo::Connection mongo("mongodb.example.org", [](React::Mongo::Connection *connection, const char *error) { // if no error occured, we will receive a null pointer if (!error) std::cout << "Connected successfully" << std::endl; // otherwise, we will get a description of what exactly went wrong else std::cout << "Connection error: " << error << std::endl;});/** * The mongo object will be created immediately, even though the connection * might not have been established. It is safe, however, to immediately run * the next command on the object. They will be executed after a connection * was established. Should the library fail to connect, all registered calls * will receive an error. */// build a query to find a specific documentVariant::Value query;query["_id"] = "documentid";// retrieve the documentmongo.query("database.collection", std::move(query)).onSuccess([](Variant::Value&& result) { // since we search for an exact id, we will get a maximum of one result // however, this result will always be an array if (result.size() == 0) { std::cout << "Could not find any document with that ID" << std::endl; return; } // assume that the document has a string field named 'firstname' std::string firstname = result[0]["firstname"];}).onError([](const char *error) { std::cout << "Something went wrong querying: " << error << std::endl;});
评论