Skip to content

Instantly share code, notes, and snippets.

@ermiry
Last active April 28, 2020 14:53
Show Gist options
  • Save ermiry/9e48a1a4468ae7cb0136f2214ef9be71 to your computer and use it in GitHub Desktop.
Save ermiry/9e48a1a4468ae7cb0136f2214ef9be71 to your computer and use it in GitHub Desktop.
#include "mongo.h"
// opens handle to user collection
int users_collection_get (void) {
int errors = 0;
users_collection = mongo_collection_get (USERS_COLL_NAME);
if (!users_collection) {
log_msg (stderr, LOG_ERROR, LOG_NO_TYPE, "Failed to get handle to users collection!");
errors = 1;
}
return errors;
}
// connect to mongo db with username & password and get handles to collections
static int connect_to_mongo (const char *password_input) {
int retval = 1;
if (password_input) {
// prepare to connect to mongo
bool connected_to_mongo = false;
// set mongo credentials and connection values
mongo_set_host (HOST_IP);
mongo_set_port (MONGO_PORT);
mongo_set_username (USER);
mongo_set_password (password_input);
mongo_set_app_name ("handler");
mongo_set_db_name ("ermiry");
char *mongo_uri = mongo_uri_generate ();
if (mongo_uri) {
mongo_set_uri (mongo_uri);
if (!mongo_connect ()) {
// test mongo connection
if (!mongo_ping_db ()) {
log_success ("Connected to Mongo DB!");
connected_to_mongo = true;
// open handle to users collection
retval = users_collection_get ();
}
}
free (mongo_uri);
}
if (!connected_to_mongo) {
log_msg (stderr, LOG_ERROR, LOG_NO_TYPE, "Failed to connect to mongo");
}
}
return retval;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment