Created
October 27, 2014 04:02
-
-
Save toinetoine/91c6443b8a9c72054671 to your computer and use it in GitHub Desktop.
App.js for reading data from Mongo. From 'Building a RESTful API' (post at http://www.antoinedahan.com/blog/BuildingRESTfulAPI/)
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
/* express initialization */ | |
var express = require('express'); | |
var app = express(); | |
/* body-parser initialization (use the body-parser json package) */ | |
var bodyParser = require('body-parser'); | |
app.use(bodyParser.json()); | |
/* Main Router */ | |
var ourApiRouter = express.Router(); | |
//Function that's called when /api/ is accessed | |
ourApiRouter.use(function (req, res, next) { | |
var requestFullPath = req.originalUrl; | |
if(requestFullPath != null) { | |
//Parse the lastname from the url | |
var lastName = requestFullPath.substring(requestFullPath.indexOf('api/') + 4); | |
var MongoClient = require('mongodb').MongoClient; | |
var format = require('util').format; | |
//Accessing the local mongo database named 'test' (mongo's default port is 27017) | |
MongoClient.connect('mongodb://127.0.0.1:27017/test', function (err, db) { | |
if (err) { | |
throw err; | |
} else { | |
//Read the entire collection 'players' from the database | |
var collection = db.collection('players'); | |
//Of the entire collection, find the one with the name attribute matching the lastname from the url | |
collection.find({name: {$regex: '^[A-z]+[ ]+' + lastName + '$'}}).toArray(function (err, docs) { | |
if(docs == null || docs.length == 0) { | |
res.json({ ERROR : "No player foudn with last name: " + lastName}); | |
} | |
else { | |
res.json(docs[0]); | |
console.log(docs[0]); | |
} | |
}); | |
} | |
}); | |
} | |
}); | |
//Registering the main router | |
app.use('/api/', ourApiRouter); | |
//Add our app the the module | |
module.exports = app; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment