Cursor exhausted when code using mongocxx is refactored into two functions instead of one

31 Views Asked by At

The following for_each method successfully connects through to the database, and the cursor allows it to loop through all the documents in the collection.

My aim is to refactor the "connecting to database and get collection" part of this method. So we also have a refactoring get_collection method implementing the first 3 lines in the try block.

void MyClass::for_each(const std::string &collectionName, std::function<void(nlohmann::json &)> func)
{
  try{
    mongocxx::client client{mongocxx::uri(uri_string)};
    mongocxx::database testing_db = client.database("db_name");
    mongocxx::collection coll = testing_db.collection(collectionName);
    //auto coll = get_collection("db_name", "Users");
    mongocxx::cursor cursor_users_all = coll.find({});
    for (auto&& doc : cursor_users_all) {
      nlohmann::json j = nlohmann::json::parse(bsoncxx::to_json(doc)) ;
      func(j);
    }
  } catch (const std::exception& e) {
    std::cerr << "An error occurred: " << e.what() << std::endl;
  }
}

mongocxx::collection MyClass::get_collection(const std::string &db_name, const std::string &collectionName)
{
  mongocxx::client client{mongocxx::uri(uri_string)};
  mongocxx::database testing_db = client.database(db_name);
  mongocxx::collection coll = testing_db.collection(collectionName);
  return coll;
}

When using the commented line instead of the 3 preceding lines: The catch block prints: An error occurred: Another cursor derived from this client is in exhaust.: generic server error. The exception happens at the for loop line.

Why is it that we cannot return a collection object? I have also tried wrapping it in a shared pointer with std::move. Is there no way to refactor this code?

0

There are 0 best solutions below