Reputation: 93
Trying to set up a simple MongoDB
database connection in Windows 7, using the C++ driver
. I'm using Visual C++ compiler 19
for x86
, 32-bit MongoDB 3.0.6
, Boost 1_59_0
, Mongo legacy 1.0.5 C++ driver
.
Driver compiles OK using the command
scons --cpppath=d:\boost_1_59_0 --libpath=d:\boost_1_59_0\stage\lib --msvc-host-arch=x86 install
Program is
#include <cstdlib>
#include <iostream>
using namespace std;
#include <WinSock2.h>
#include <windows.h>
#include "mongo/client/dbclient.h"
void run() {
mongo::DBClientConnection c;
c.connect("localhost");
}
int main() {
try {
run();
std::cout << "connected ok" << std::endl;
} catch( const mongo::DBException &e ) {
std::cout << "caught " << e.what() << std::endl;
}
return EXIT_SUCCESS;
}
Program compiles using
cl /EHsc /I"c:\mongo-cxx-driver-legacy-1.0.5\build\install\include" /I"d:\boost_1_59_0" /DSTATIC_LIBMONGOCLIENT mdb.cpp c:\mongo-cxx-driver-legacy-1.0.5\build\install\lib\libmongoclient-s.lib /link /LIBPATH:"D:\boost_1_59_0\stage\lib" ws2_32.lib
But when I run the program, get the error message
caught can't connect couldn't initialize connection to localhost
, address is invalid
The server
is running OK as I can access it through the shell
, add records etc.
This is my first time programming MongoDB
and I'm kind of stuck. Any suggestions?
Upvotes: 2
Views: 2207
Reputation: 93
OK, problem solved (thanks to stevepowell.ca/mongo-db-1.html). Here's the answer for anyone else who runs into this problem:
Windows needs to initialize the client before setting up the connection.
#include <cstdlib>
#include <iostream>
#include <WinSock2.h>
#include <windows.h>
#include <memory>
#include "mongo/client/dbclient.h"
using namespace mongo;
using namespace std;
void run() {
mongo::client::initialize(); // this line is new
mongo::DBClientConnection c;
c.connect("localhost");
}
int main() {
try {
run();
std::cout << "connected ok" << std::endl;
} catch( const mongo::DBException &e ) {
std::cout << "caught " << e.what() << std::endl;
}
return EXIT_SUCCESS;
}
I wish this had been in the tutorial!
Onwards and upwards.
Upvotes: 2