Skip to content

Instantly share code, notes, and snippets.

@fwielstra
Created June 14, 2011 14:46
Show Gist options
  • Select an option

  • Save fwielstra/1025038 to your computer and use it in GitHub Desktop.

Select an option

Save fwielstra/1025038 to your computer and use it in GitHub Desktop.
An example NodeJS / Mongoose / Express application based on their respective tutorials
/* 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');
exports.post = function(req, res) {
new Thread({title: req.body.title, author: req.body.author}).save();
}
exports.list = function(req, res) {
Thread.find(function(err, threads) {
res.send(threads);
});
}
// first locates a thread by title, then locates the replies by thread ID.
exports.show = (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
mongoose.connect('mongodb://localhost/norum');
app.configure(function(){
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
// set up the RESTful API, handler methods are defined in api.js
var api = require('./controllers/api.js');
app.post('/thread', api.post);
app.get('/thread/:title.:format?', api.show);
app.get('/thread', api.list);
app.listen(3000);
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: Date.now},
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: Date.now},
author: {type: String, default: 'Anon'}
});
module.exports = mongoose.model('Thread', threadSchema);
@takecian
Copy link
Copy Markdown

thanks!

@adriancooney
Copy link
Copy Markdown

Thanks!

@djmccormick
Copy link
Copy Markdown

Thank you!

@mattjburrows
Copy link
Copy Markdown

This is really helpful and has clarified the mongoose docs for me.

Cheers!

@angelomiranda
Copy link
Copy Markdown

Aw, my head hurts all of a sudden! Thanks buddy...

@Deacs
Copy link
Copy Markdown

Deacs commented Oct 8, 2013

Thanks!

@anil3a
Copy link
Copy Markdown

anil3a commented Nov 1, 2013

Can you please update the Codes? It sends error now and i did modify some codes but didn't get it working still. Please help.

@ayasuda2OO3
Copy link
Copy Markdown

nice structure.

@ethanmuller
Copy link
Copy Markdown

This helped me out. Thanks for posting this! 🍺

Copy link
Copy Markdown

ghost commented Nov 26, 2013

that's just awesome !
helped a lot

@fatchat
Copy link
Copy Markdown

fatchat commented Dec 8, 2013

Very nicely written, good organization, no unnecessary details. Thank you!

@tony-kerz
Copy link
Copy Markdown

thanks man, this is helpful, they should make it part of the docs. the quick-start is a little thin ;)

i'm kind of new to javascript/node, one thing i'm not clear on are idioms for robust error handling in a node app,
any ideas around that you could share would be helpful.

regards,
tony.

@melbourne2991
Copy link
Copy Markdown

friggin awesome cheers!

@ohadperry
Copy link
Copy Markdown

great!

@ADelRosarioH
Copy link
Copy Markdown

THANKS!!!

@m00s
Copy link
Copy Markdown

m00s commented Jul 18, 2014

Really helpful! Thanks

@maisnamraju
Copy link
Copy Markdown

Much Thanks for this.

@suminsudhi
Copy link
Copy Markdown

Thanks a lot. Was very helpful 👍

@gkoberger
Copy link
Copy Markdown

I made a repo based on this:

https://github.com/gkoberger/express4-mongoose-api-example

Upgraded to Express 4, as well as included a package.json and instructions on how to run it.

@elrrrrrrr
Copy link
Copy Markdown

Good !

@bubakazouba
Copy link
Copy Markdown

thank you

@alexlebed
Copy link
Copy Markdown

Спасибо. Очень понятно. Thank you

@macdonjo
Copy link
Copy Markdown

macdonjo commented Apr 4, 2016

What exactly is body in req.body?

@ltouro
Copy link
Copy Markdown

ltouro commented Aug 16, 2016

@macdonjo the body of HTTP request sent by the client. On a HTTP Post request, the body can be anything. In this sample, is a JSON object, which is parsed from a string by the express.bodyParser()

@MarcusFleck
Copy link
Copy Markdown

Thanks, thats exactly what i was looking for

@yvanwangl
Copy link
Copy Markdown

Thank you. This demo help me a lot !

@Karthik248
Copy link
Copy Markdown

Great demo as a starting point. Thanks.

@c0d0g3n
Copy link
Copy Markdown

c0d0g3n commented Apr 10, 2017

What about checking whether Mongoose actually connected to the database or whether an error was thrown? (as seen in code snippet 3 at http://mongoosejs.com/docs/index.html) I came here wondering (I'm new to this matter, too) if all following application logic (e.g. routes) should go into the callback of the 'open' event, but unfortunately didn't find a solution. (I assume it should go there, but that looks odd, doesn't it?)

Regardless, thanks for sharing you knowledge with the community!

@awhitehouse104
Copy link
Copy Markdown

awhitehouse104 commented Apr 13, 2017

@c0d0g3n Came wondering the same thing, mongoose docs you reference make it sound important then sort of gloss over it at the same time

@lgutie16
Copy link
Copy Markdown

Thank you! you are the best!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment