Skip to content

Instantly share code, notes, and snippets.

@chrisckchang
Created April 23, 2015 05:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save chrisckchang/4a258c53a78631690001 to your computer and use it in GitHub Desktop.
Save chrisckchang/4a258c53a78631690001 to your computer and use it in GitHub Desktop.
replica set connection with nodejs native
/**
* MongoDB NodeJS Driver Production Connection Example
*
* Copyright (c) 2015 ObjectLabs Corporation
* Distributed under the MIT license - http://opensource.org/licenses/MIT
*/
var MongoClient = require('mongodb').MongoClient;
/**
* The following example uses node-mongodb-native 2.0.21 to connect to a MongoDB deployment using the options we have
* found most appropriate to production applications. This example supports both replica set and SSL connections.
*
* For demonstration purposes, configuration is hard-coded; in practice, configuration should be externalized
* e.g. into a file or environment variables.
*/
/**
* Your deployment's URI in the standard format (http://docs.mongodb.org/manual/reference/connection-string/).
*
* The URI can be found via the MongoLab management portal (http://docs.mongolab.com/connecting/#connect-string).
*
* If you are using a PaaS add-on integration e.g. via Heroku, the URI is usually available via an environment variable,
* often named "MONGOLAB_URI". Consult the documentation for the add-on you are using.
*/
var mongolab_uri = "mongodb://<dbUser>:<dbPassword>@<host1>:<port1>,<host2>:<port2>/<dbName>?replicaSet=<replicaSetName>";
/**
* Pass the following keyword arguments to ensure proper production behavior:
*
* autoReconnect True to reconnect on error
*
* keepAlive Enabled (1) to ensure idle connections are kept alive in the presence of a firewall.
*
* connectTimeoutMS 30 s to allow for PaaS warm-up; adjust down as needed for faster failures. For more, see docs:
* http://docs.mongolab.com/timeout/#connection-timeout
*
* socketTimeoutMS No timeout (0) to allow for long-running operations
* (http://docs.mongolab.com/timeout/#socket-timeout).
*
* See Nodejs Native docs for more details about the connection options:
*
* http://mongodb.github.io/node-mongodb-native/2.0/api/MongoClient.html
*/
var options = {
server: {
socketOptions: {
autoReconnect: true,
keepAlive: 1,
connectTimeoutMS: 30000,
socketTimeoutMS: 0
}
},
replSet: {
socketOptions: {
keepAlive: 1,
connectTimeoutMS: 30000,
socketTimeoutMS: 0
}
}
}
MongoClient.connect(mongolab_uri, options, function(err, db){
if(err){
console.log(err);
} else {
db.collections(function(err, collections) {
collections.forEach(function(coll) {
console.log(coll.s.name);
});
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment