无法从C++代码

问题描述:

Windows 7中,msys2,编译器的MinGW无法从C++代码

试图连接到从C++代码的MongoDB实例连接到MongoDB的。下一个命令运行mongod

mongod --dbpath ./dev-db --bind_ip 127.0.0.1 --port 27017 

我可以正常通过mongo和Robomongo连接到这个数据库中。

对于C++代码,我成功编译并安装了上一个稳定的Mongo C++ Driver。代码我从官方tutorial

#include <mongocxx/client.hpp> 
#include <mongocxx/instance.hpp> 
#include <mongocxx/uri.hpp> 

mongocxx::uri uri("mongodb://127.0.0.1:27017"); 
mongocxx::client conn{uri}; 
auto db = conn["test"]; 

bsoncxx::document::value restaurant_doc = 
    document{} << "address" << open_document << "street" 
       << "2 Avenue" 
       << "zipcode" 
       << "10075" 
       << "building" 
       << "1480" 
       << "coord" << open_array << -73.9557413 << 40.7720266 << close_array 
       << close_document << "borough" 
       << "Manhattan" 
       << "cuisine" 
       << "Italian" 
       << "grades" << open_array << open_document << "date" 
       << bsoncxx::types::b_date{std::chrono::milliseconds{12323}} << "grade" 
       << "A" 
       << "score" << 11 << close_document << open_document << "date" 
       << bsoncxx::types::b_date{std::chrono::milliseconds{121212}} << "grade" 
       << "B" 
       << "score" << 17 << close_document << close_array << "name" 
       << "Vella" 
       << "restaurant_id" 
       << "41704620" << finalize; 
auto res = db["restaurants"].insert_one(std::move(restaurant_doc)) 

这提供了一个错误:

This application has requested the Runtime to terminate it in an unusual way. 
Please contact the application's support team for more information. 
terminate called after throwing an instance of 'mongocxx::v_noabi::bulk_write_exception' 
    what(): No suitable servers found (`serverSelectionTryOnce` set): [Failed to resolve '127.0.0.1']: generic server error 

我如何才能避免这一问题,并连接到数据库?

你拷贝丢失的例子的第一行:

mongocxx::instance inst{};

http://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/#make-a-connectionmongocxx::instance构造函数和析构函数分别初始化和关闭驱动程序,因此必须在使用该驱动程序之前创建mongocxx::instance,并且只要该驱动程序正在使用,必须保持活动状态。

它看起来像是尝试DNS查找127.0.0.1。试着改变它是localhost,而不是(这将解析到同一个IP)

mongocxx::uri uri("mongodb://localhost:27017"); 
+0

使用localhost不起作用。它只是显示'[无法解析'localhost']'而是。 – Serbin