I'm programming a server side C++ music application. I'm stuck with the Database part, I choose MongoDB to go with and I'm not the boss in C++.
I made a Database class which stores the MongoDB unique instance and I would like to create multiple MongoDB clients on the fly like this
this->setDatabaseURI(&this->uri, "mongodb://localhost:27017");
mongocxx::client *cli1 = this->createNewClient();
mongocxx::client *cli2 = this->createNewClient();
mongocxx::client *cli3 = this->createNewClient();
auto db1 = cli1["myAppDB"];
auto db2 = cli2["myAppDB"];
auto db3 = cli3["myAppDB"];
compiler says:
PATH/Database.cpp:31:20: error: array subscript is not an integer
auto db1 = cli1["myAppDB"];
^~~~~~~~~~
PATH/Database.cpp:32:20: error: array subscript is not an integer
auto db2 = cli2["myAppDB"];
^~~~~~~~~~
PATH/Database.cpp:33:20: error: array subscript is not an integer
auto db3 = cli3["myAppDB"];
^~~~~~~~~~
3 errors generated.
The goal was to create clients on the fly using pointers and call the createNewClient() function when a new client is needed.
mongocxx::client *Database::createNewClient()
{
mongocxx::client *cli = new mongocxx::client();
return (cli);
}
if I do like this it works:
mongocxx::client conn;
auto db = conn["myAppDB"];
I don't understand why? What "[]" are in this situation?
You try to call [] operator on the pointer, which obviously does not work. You should dereference pointer and call it on the object instance instead:
auto d = (*cli1)["myAppDB"];