Skip to content

Instantly share code, notes, and snippets.

@tfogo
Last active May 26, 2016 09:14
Show Gist options
  • Save tfogo/8657363 to your computer and use it in GitHub Desktop.
Save tfogo/8657363 to your computer and use it in GitHub Desktop.
RESTful API with node.js and mongodb. `npm install` then `node server.js`
var mongoose = require('mongoose')
, Podcast = mongoose.model('Podcast');
Podcast.find({}).remove(function() {
Podcast.create({
title: 'Joe Rogan',
score: 4783,
tags: ['tag1', 'tag2', 'tag3'],
dateSubmitted: new Date
}, {
title: 'Night Vale',
score: 124,
tags: ['tag1', 'tag2', 'tag3'],
dateSubmitted: new Date
}, {
title: 'Rooster Teeth',
score: 10,
tags: ['tag1', 'tag2', 'tag3'],
dateSubmitted: new Date
}, function(err) {
console.log('finished populating podcasts');
});
});
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
// Schema
var PodcastSchema = new Schema({
title: String,
score: Number,
tags: [String],
dateSubmitted: Date
});
mongoose.model('Podcast', PodcastSchema);
{
"name": "apiExample",
"version": "0.0.1-30",
"dependencies": {
"express": "~3.4.3",
"mongoose": "~3.5.5"
},
"engines": {
"node": ">=0.8.0"
}
}
var mongoose = require('mongoose')
, Podcast = mongoose.model('Podcast');
exports.allPodcasts = function(req, res) {
Podcast.find(function(err, podcasts) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(podcasts);
}
});
};
exports.searchPodcasts = function(req, res) {
Podcast.find({title: req.param('title')}, function(err, podcasts) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(podcasts);
}
});
};
var express = require('express')
var http = require('http');
var app = express();
var mongoose = require('mongoose');
// mongoose models
require('./models');
// routes
var routes = require('./routes');
// mongodb URI
var uristring =
process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URI ||
'mongodb://localhost/node9000';
// connect to db
mongoose.connect(uristring);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));require('./models');
db.once('open', function(){
console.log("Mongoose started!");
require('./dummydata'); // populates db with dummy data
});
// express config
app.use(app.router);
// routes
app.get('/all', routes.allPodcasts);
app.get('/search', routes.searchPodcasts); // try /search?title=Night+Vale
// start server
server = http.createServer(app);
server.listen(process.env.PORT || 8000);
console.log('Express server started on port %s', server.address().port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment