How to re-connect to MongoDB using C++ driver?

2019-08-29 03:37发布

问题:

I've a C++ function which saves a document to MongoDB using C++ driver. It takes connection reference as argument:

http://pastebin.com/jwRDhNWQ

When I restart MongoDB, I can see that new connection is being made. However, conn.isFailed() remains true.

This maybe happening due to the fact that when I reconnect, I am using conn and not &conn When I do use &conn as in &conn.connect("localhost");, I get error message-

error: lvalue required as unary ‘&’ operand

How do I fix this? i.e. modify the underlying connection so that conn.isFailed() becomes false when a new connection has been established?

回答1:

You should enable _autoReconnect in the mongo::DBClientConnection::DBClientConnection constructor.
http://api.mongodb.org/cplusplus/current/classmongo_1_1_d_b_client_connection.html#a6a1a348024dd302572504b7bfb6e74a2

The variable _failed returned by the method isfailed() is not set until _check Connection is called. _checkConnection is not called until something is sent to the database, so as an alternative, you could call the ping command before calling _isFailed. However, the recommended fix is to enable _autoReconnect.