Search code examples
mongodbmongo-cxx-driver

Mongodb c++ crashing when inserting into collection inside an object


I am using the mongocxx driver and I am trying to do a basic insert into a collection.

If I simply follow the guidelines presented here, it works fine.

However, if I put the db and collection instances inside an object, the insert crashes at runtime. So, for a simple example, I have a struct with the database and collection instances, and the try to do an insert via these instances after creating an instance of Thing in main():

#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/types.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/instance.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>


struct Thing {
   mongocxx::client client;
   mongocxx::database db;
   mongocxx::collection coll;

   void open_connection(const char* host, const char* db_name, const char* coll_name) {
      mongocxx::instance inst{};
      mongocxx::uri uri(host);

      client = mongocxx::client::client(uri);
      db = client[db_name];
      coll = db[coll_name];
   }
};


int main()
{
   Thing thing;
   thing.open_connection("mongodb://localhost:27017", "test", "insert_test");

   auto builder = bsoncxx::builder::stream::document{};
   bsoncxx::document::value doc_value = builder << "i" << 1 << bsoncxx::builder::stream::finalize;

   auto res = thing.coll.insert_one(doc_value.view()); //crashes

   return 0;
}

I realize this can be solved by initiating the database and collection in main and storing only a pointer to the collection inside Thing. I am however wondering about the reason for the crash, and whether it is possible to put the db an collection instances inside an object at all.


Solution

  • I think the problem could be that mongocxx::instance inst{}; created on stack in open_connection, so at the end of open_connection the inst is destroyed and some data may become undefined.

    From documentation:

    Life cycle: A unique instance of the driver MUST be kept around.

    Move inst to the main function.