Skip to content

Instantly share code, notes, and snippets.

@ratfactor
Created October 14, 2013 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ratfactor/6980657 to your computer and use it in GitHub Desktop.
Save ratfactor/6980657 to your computer and use it in GitHub Desktop.
An example of using Mongoose for Node.js to implement a toy blog application in Node.js.
var mongoose = require('mongoose');
var postSchema = new mongoose.Schema({ title: String, body: String, date: Date });
var Post = mongoose.model('Post', postSchema);
mongoose.connect('mongodb://localhost/blog');
var db = mongoose.connection;
db.once('open', function(){ startServer(); });
function startServer(){
var connect = require('connect');
var server = connect();
var dispatch = require('dispatch');
server.use(connect.bodyParser());
server.use(dispatch({
'GET /': function(req, res, next){ index(res); },
'POST /posts': function(req, res, next){ newpost(req, res); },
'GET /posts/:id': function(req, res, next, id){ viewpost(res, id); }
}));
server.listen(80);
console.log("Server has started.");
}
function index(res){
Post.find({}, function(err, posts){
if(err){ throw err; }
res.write("<html><head><title>Superblog</title></head><body><h1>Superblog!</h1><ul>");
posts.forEach(function(post){
res.write('<li><a href="/posts/'+post._id+'">'+post.title+'</a></li>');
});
res.write('</ul><form action="/posts" method="post">');
res.write('Title<br><input type="text" name="title"><br>');
res.write('Body<br><textarea name="body"></textarea><br>');
res.write('<input type="submit"></form>');
res.end('</body></html>');
});
}
function newpost(req, res){
var b = new Post({ title: req.body.title, body: req.body.body, date: Date.now() });
b.save(function(err){
if(err){ throw(err); }
index(res);
});
}
function viewpost(res, id){
Post.findOne({_id:id}, function(err, post){
res.end('<html><head><title>'+post.title+' - Superblog</title></head><body><h1>'+post.title+'</h1><b>Posted on '+post.date+'</b><p>'+post.body+'</p></body></html>');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment