Skip to content

Instantly share code, notes, and snippets.

@tlivings
Created January 26, 2012 00:48
Show Gist options
  • Select an option

  • Save tlivings/1680081 to your computer and use it in GitHub Desktop.

Select an option

Save tlivings/1680081 to your computer and use it in GitHub Desktop.
Sample MongoDB connection that uses node-mongodb-native and connects with URIs
/*
* Usage example:
* var MongoConnection = require('./mongoconnection').MongoConnection;
* mongo_connection = new MongoConnection(process.env.MONGOHQ_URL);
*
* See also: https://github.com/christkv/node-mongodb-native
*
* Hat tip to: http://howtonode.org/express-mongodb
*/
MongoConnection = function(mongo_uri) {
require('mongodb').connect(mongo_uri, {auto_reconnect: true}, function(error,_db) {
if(error) {
console.log(error);
}
else {
console.log('Connected to Mongo');
MongoConnection.prototype.db = _db;
}
})
};
//Get the specified collection
MongoConnection.prototype.getCollection = function(collection_name, callback) {
this.db.collection(collection_name, function(error, collection) {
if( error ) callback(error);
else callback(null, collection);
});
};
//Find all objects in a collection
MongoConnection.prototype.findAll = function(collection_name, callback) {
this.getCollection(collection_name, function(error, collection) {
if( error ) callback(error)
else {
collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
//Find an object by id in a collection
MongoConnection.prototype.findById = function(collection_name, id, callback) {
this.getCollection(collection_name, function(error, collection) {
if( error ) callback(error)
else {
collection.findOne({_id: collection.db.bson_serializer.ObjectID.createFromHexString(id)}, function(error, result) {
if( error ) callback(error)
else callback(null, result)
});
}
});
};
//Save an object to a collection
MongoConnection.prototype.save = function(collection_name, objects, callback) {
this.getCollection(collection_name, function(error, collection) {
if(error) callback(error)
else {
if( typeof(objects.length)=="undefined") {
objects = [objects];
}
collection.insert(objects, function() {
callback(null, objects);
});
}
});
};
exports.MongoConnection = MongoConnection;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment