2

I installed mongocxx driver successfully. Now I tried to write a class to connect and query data from database. If I write a query in constructor like this

DBConnection::DBConnection()
{
    mongocxx::instance instance{};
    mongocxx::uri uri("mongodb://localhost:27017");
    mongocxx::client client(mongocxx::uri{});
    coll = client["testdb"]["testcollection"];
    auto curs = coll.find(bsoncxx::builder::stream::document{} << finalize);
    for (auto doc: curs) {
        std::cout << bsoncxx::to_json(doc) << "\n";
    }
}

it works like a charm.

But, if I separate in two functions like this

DBConnection::DBConnection()
{
    mongocxx::instance instance{};
    mongocxx::uri uri("mongodb://localhost:27017");
    mongocxx::client client(mongocxx::uri{});
    coll = client["testdb"]["testcollection"];
}

void DBConnection::loadData() {
    mongocxx::cursor cursor = coll.find({});
    for (auto doc: cursor) {
        std::cout << bsoncxx::to_json(doc) << "\n";
    }    
}

then, it gave the error: src/mongoc/mongoc-topology-scanner.c:754 mongoc_topology_scanner_get_error(): precondition failed: ts.

I don't know why. How can I fix this?

GAVD
  • 1,977
  • 3
  • 22
  • 40

1 Answers1

1

The lifetime of the mongocxx::collection object is required to be a subset of the lifetime of the mongocxx::client object that created it. You have violated that constraint by obtaining the mongocxx::client object in the constructor, then obtaining and storing the mongocxx::collection object in (what is presumably a) member variable of the class, and then allowing the mongocxx::client object to be destroyed. The subsequent use of the mongocxx::collection object in loadData invalid.

acm
  • 12,183
  • 5
  • 39
  • 68