Skip to content

Instantly share code, notes, and snippets.

@sturadnidge
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturadnidge/6dd4f28fff036a67d325 to your computer and use it in GitHub Desktop.
Save sturadnidge/6dd4f28fff036a67d325 to your computer and use it in GitHub Desktop.
Generic MongoDB lib for use with Express 4 apps
'use strict';
var db,
MongoClient = require('mongodb').MongoClient;
var database_name = checkExists(process.env.MONGODB_DATABASE) ? process.env.MONGODB_DATABASE : 'test',
env_user = process.env.MONGODB_USER,
env_pass = process.env.MONGODB_PASSWORD,
env_host = checkExists(process.env.MONGODB_HOST) ? process.env.MONGODB_HOST : 'localhost',
env_port = checkExists(process.env.MONGODB_PORT) ? parseInt(process.env.MONGODB_PORT, 10) : 27017;
var connString = env_host + ":" + env_port + "/" + database_name;
if (checkExists(env_user)) {
connString = env_user + ":" + env_pass + "@" + connString;
}
MongoClient.connect("mongodb://" + connString,
function(err, database) {
if (!database) {
console.log('eeeek! no database!');
} else {
db = database;
console.log('using database: ' + database_name + ' on ' + env_host + ':' + env_port);
}
}
);
module.exports = {
remove: function(name, query, callback) {
db.collection(name).remove(query, callback);
},
removeOne: function(name, item, callback) {
module.exports.remove(name, item, function(err, items) {
callback(err, items[0]);
});
},
find: function(name, query, limit, callback) {
db.collection(name)
.find(query)
.sort({created: -1})
.limit(limit)
.toArray(callback);
},
findOne: function(name, query, callback) {
db.collection(name).findOne(query, callback);
},
insert: function(name, items, callback) {
db.collection(name).insert(items, callback);
},
// inserts a single document and returns it to the caller
insertOne: function(name, item, callback) {
module.exports.insert(name, item, function(err, items) {
callback(err, items[0]);
});
},
// update using id property of an item
// return the item to the caller via findOne
updateById: function(name, id, updateQuery, callback) {
db.collection(name).update({id: id},
{$set: updateQuery},
function(err, count) {
module.exports.findOne(name, {id: id}, callback)
});
},
// update using a query selector
// return the item to the caller via findOne
updateByQuery: function(name, selectorQuery, updateQuery, callback) {
db.collection(name).update(selectorQuery,
{$set: updateQuery},
function(err, count) {
module.exports.findOne(name, selectorQuery, callback)
});
}
}
// unexported
function checkExists(x) { return x != null };
@sturadnidge
Copy link
Author

Uses the 'new' style of the MongoClient and conventions for node driver 1.4.7.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment