Last active
September 15, 2015 15:19
-
-
Save jeff-hager-dev/86c4f63eb938b2dab010 to your computer and use it in GitHub Desktop.
A super simple base controller that a swagger API can use to do queries of a mongoDB table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongodb = require('mongodb'); | |
var MongoClient = mongodb.MongoClient; | |
var baseController = function (collectionName) { | |
var _settings = { | |
url: 'mongodb://localhost:27017/ghfive', | |
collectionName: collectionName | |
}; | |
this.default = { | |
get: function (req, res) { | |
MongoClient.connect(_settings.url, function (err, db) { | |
var collection = db.collection(_settings.collectionName); | |
var query = req.query; | |
var fieldFilter = {'_id': 0}; | |
if (query.selectedFields) { | |
var onlyFields = query.selectedFields.split(','); | |
for (var idx in onlyFields) { | |
fieldFilter[onlyFields[idx]] = 1 | |
} | |
delete query.selectedFields; | |
} | |
if (query.excludeFields) { | |
fieldFilter = {'_id': 0}; | |
var excludeFields = query.excludeFields.split(','); | |
for (var idx in excludeFields) { | |
fieldFilter[excludeFields[idx]] = 0 | |
} | |
delete query.excludeFields; | |
} | |
var skip = query.skip || -1; | |
var limit = query.limit || -1; | |
if (skip) { | |
delete query.skip; | |
} | |
if (limit) { | |
delete query.limit; | |
} | |
for (var prop in query) { | |
var propVal = query[prop]; | |
query[prop] = {'$regex': new RegExp("^" + propVal.toLowerCase(), "i")}; | |
} | |
var cursor = collection.find(query, fieldFilter); | |
if (skip > -1) { | |
cursor.skip(parseInt(skip)); | |
} | |
if (limit > -1) { | |
cursor.limit(parseInt(limit)); | |
} | |
cursor.toArray(function (err, doc) { | |
res.status(200).json({data: doc}); | |
}); | |
}); | |
} | |
}; | |
}; | |
module.exports = baseController; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment