Skip to content

Instantly share code, notes, and snippets.

Forked from fwielstra/api.js
Created June 21, 2014 18:19
Show Gist options
  • Save rogeruiz/41c2f0ad5fde33aaf662 to your computer and use it in GitHub Desktop.
Save rogeruiz/41c2f0ad5fde33aaf662 to your computer and use it in GitHub Desktop.
/* The API controller
Exports 3 methods:
* post - Creates a new thread
* list - Returns a list of threads
* show - Displays a thread and its posts
var Thread = require('../models/thread.js');
var Post = require('../models/post.js'); = function(req, res) {
new Thread({title: req.body.title, author:}).save();
exports.list = function(req, res) {
Thread.find(function(err, threads) {
// first locates a thread by title, then locates the replies by thread ID. = (function(req, res) {
Thread.findOne({title: req.params.title}, function(error, thread) {
var posts = Post.find({thread: thread._id}, function(error, posts) {
res.send([{thread: thread, posts: posts}]);
// The main application script, ties everything together.
var express = require('express');
var mongoose = require('mongoose');
var app = module.exports = express.createServer();
// connect to Mongo when the app initializes
// set up the RESTful API, handler methods are defined in api.js
var api = require('./controllers/api.js');'/thread',;
app.get('/thread', api.list);
console.log("Express server listening on port %d", app.address().port);
// The Post model
var mongoose = require('mongoose')
,Schema = mongoose.Schema
,ObjectId = Schema.ObjectId;
var postSchema = new Schema({
thread: ObjectId,
date: {type: Date, default:},
author: {type: String, default: 'Anon'},
post: String
module.exports = mongoose.model('Post', postSchema);
// The Thread model
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var threadSchema = new Schema({
title: String,
postdate: {type: Date, default:},
author: {type: String, default: 'Anon'}
module.exports = mongoose.model('Thread', threadSchema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment