【分享】C++ MongoDB驱动带权限连接代码实现(针对legacy驱动)

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【分享】C++ MongoDB驱动带权限连接代码实现(针对legacy驱动)

mongodb的权限配置可以参考该文:【整理】CentOS 6.5 mongodb 3.2增加权限配置

C++代码中如果带权限连接,那么可以参考如下代码段:

try {
			mongo::DBClientConnection *conn = new mongo::DBClientConnection(auto_conn, 0, time_out);
			if (conn != NULL)
			{
				conn->connect("localhost");
				conn->auth(BSON("mechanism"<< "SCRAM-SHA-1" << "user" << "admin" << "pwd" << "admin" << "db" << "test_db"));
			}
		}
		catch (const mongo::ConnectException &e) {
			std::cout << "MongoDB无法访问! 问题:" << e.what() << std::endl;
			this->db_connect_status = false;
		}
		catch (const mongo::SocketException &e) {
			std::cout << "MongoDB无法访问! 问题:" << e.what() << std::endl;
			this->db_connect_status = false;
		}
		catch (const mongo::DBException &e) {
			std::cout << "MongoDB无法访问! 问题:" << e.what() << std::endl;
			this->db_connect_status = false;
		}

只要调用auth函数即可,函数原型为:

参考链接:https://mongodb.github.io/mongo-cxx-driver/api/legacy-1.1.2/classmongo_1_1DBClientWithCommands.html#aef21a401b2151f3f35c77c0b9c7e00d0

QQ截图20170531230159

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【分享】C++ MongoDB驱动带权限连接代码实现(针对legacy驱动)

文章的脚注信息由WordPress的wp-posturl插件自动生成



|2|left
打赏

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: