Created
January 22, 2015 15:19
-
-
Save nickludlam/23190c588df0eb93e84e to your computer and use it in GitHub Desktop.
NodeJS mini-app for querying MongoDB
This file contains 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 express = require('express') | |
, mongoskin = require('mongoskin') | |
, bodyParser = require('body-parser') | |
var path = require('path'); | |
var app = express() | |
app.set('views', path.join(__dirname, 'views')); | |
app.use(express.static(path.join(__dirname, 'public'))); | |
app.use(bodyParser()) | |
var db = mongoskin.db('mongodb://@localhost:27017/elite-dangerous-api', {safe:true}) | |
app.param('collectionName', function(req, res, next, collectionName){ | |
req.collection = db.collection(collectionName) | |
return next() | |
}) | |
app.get('/', function(req, res, next) { | |
res.send('please select a collection, e.g., /collections/messages') | |
}) | |
app.get('/collections/:collectionName', function(req, res, next) { | |
req.collection.find({} ,{ limit:10, sort: ['timestamp',-1]}).toArray(function(e, results){ | |
if (e) return next(e) | |
res.send(results) | |
}) | |
}) | |
app.get('/collections/:collectionName/at/:at_timestamp', function(req, res, next) { | |
at_timestamp = parseInt(req.params.at_timestamp) | |
req.collection.find({ timestamp: at_timestamp },{ commander: true }).toArray(function(e, results){ | |
if (e) return next(e) | |
res.send(results) | |
}) | |
}) | |
app.get('/collections/:collectionName/from/:from_timestamp/to/:to_timestamp', function(req, res, next) { | |
from_timestamp = parseInt(req.param.from_timestamp) | |
to_timestamp = parseInt(req.param.to_timestamp) | |
req.collection.find({ timestamp: { $gt: from_timestamp, $lt: to_timestamp }} ,{ sort: [['timestamp',-1]]}).toArray(function(e, results){ | |
if (e) return next(e) | |
res.send(results) | |
}) | |
}) | |
app.get('/collections/:collectionName/commodity/:commodity_name', function(req, res, next) { | |
commodity_name = req.params.commodity_name | |
req.collection.aggregate([ | |
{ $sort: { timestamp: -1 }}, | |
{ $limit : 100 }, | |
{ $match: { 'lastStarport.commodities': { $elemMatch : { 'name': commodity_name }}}}, | |
{ $unwind: '$lastStarport.commodities' }, { $match: {'lastStarport.commodities.name': commodity_name}}, | |
{ "$project": { "timestamp": 1, "lastStarport.commodities.name": 1, "lastStarport.commodities.buyPrice": 1, "lastStarport.commodities.sellPrice": 1, "lastStarport.commodities.meanPrice": 1 }} | |
], function(e, results){ | |
if (e) return next(e) | |
res.send(results) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment