Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
@loicginoux

This comment has been minimized.

Copy link

@loicginoux loicginoux commented Jul 19, 2011

Thanks for that. It helped me clarify few things...

@david-truong

This comment has been minimized.

Copy link

@david-truong david-truong commented Feb 2, 2012

Great example, thanks!

@dfucci

This comment has been minimized.

Copy link

@dfucci dfucci commented Mar 7, 2012

Thanks man, very helpful!

@tjeastmond

This comment has been minimized.

Copy link

@tjeastmond tjeastmond commented Apr 6, 2012

Perfect. Thank you for this

@bhurlow

This comment has been minimized.

Copy link

@bhurlow bhurlow commented Apr 13, 2012

yea this is a great simple example. thnx!

@y0j

This comment has been minimized.

Copy link

@y0j y0j commented Jun 6, 2012

thank you!

@elemenofi

This comment has been minimized.

Copy link

@elemenofi elemenofi commented Aug 9, 2012

LOVE!

@ultra2

This comment has been minimized.

Copy link

@ultra2 ultra2 commented Aug 24, 2012

If you want to generate source code like post.js, there is site for that: www.extsolutions.net (its free) You will install a mongoose generator.

@amirmog

This comment has been minimized.

Copy link

@amirmog amirmog commented Nov 25, 2012

Thumbs up; thank you for the time to put this out there. It definitely helped me digest the basics.
any other resources that are abit more complex to learn more?

@film42

This comment has been minimized.

Copy link

@film42 film42 commented Dec 15, 2012

This is really cool. Thanks for sharing! I wish the main project would link here (didn't seem to at least).

@jackSB

This comment has been minimized.

Copy link

@jackSB jackSB commented Dec 20, 2012

Hi there, where are the tutorials the title mentions? Seem to have stumbled here straight from a search.

@kfields

This comment has been minimized.

Copy link

@kfields kfields commented Jan 13, 2013

Exactly what I was looking for, short and simple. Thanks!

@coughski

This comment has been minimized.

Copy link

@coughski coughski commented Feb 23, 2013

@senseivchan: Yes, you need to install mongoose, which is a separate package you can get using npm.

@skbailey

This comment has been minimized.

Copy link

@skbailey skbailey commented Mar 8, 2013

Thanks! I was wondering how to include it in the project

@pdarkness

This comment has been minimized.

Copy link

@pdarkness pdarkness commented Mar 15, 2013

thanks =)

@aisipos

This comment has been minimized.

Copy link

@aisipos aisipos commented Apr 13, 2013

Liking it. But perhaps at this stage we should add tests?

@crispen-smith

This comment has been minimized.

Copy link

@crispen-smith crispen-smith commented Jun 26, 2013

Funny how there are a number of really verbose tutorials out there and sometimes all you really need is a concrete example. I'm actually building for web presentation rather than an API so there will be differences, but your code is so clean that I can see exactly where they should be and build out from there.

@kyktommy

This comment has been minimized.

Copy link

@kyktommy kyktommy commented Aug 2, 2013

Great example to me as a beginner : -]

@aymen-mouelhi

This comment has been minimized.

Copy link

@aymen-mouelhi aymen-mouelhi commented Aug 7, 2013

thank you !

@balaclark

This comment has been minimized.

Copy link

@balaclark balaclark commented Aug 16, 2013

Good stuff, thanks.

@takecian

This comment has been minimized.

Copy link

@takecian takecian commented Aug 25, 2013

thanks!

@adriancooney

This comment has been minimized.

Copy link

@adriancooney adriancooney commented Aug 25, 2013

Thanks!

@djmccormick

This comment has been minimized.

Copy link

@djmccormick djmccormick commented Sep 17, 2013

Thank you!

@mattjburrows

This comment has been minimized.

Copy link

@mattjburrows mattjburrows commented Sep 19, 2013

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

Cheers!

@angelomiranda

This comment has been minimized.

Copy link

@angelomiranda angelomiranda commented Sep 27, 2013

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

@Deacs

This comment has been minimized.

Copy link

@Deacs Deacs commented Oct 8, 2013

Thanks!

@anil3a

This comment has been minimized.

Copy link

@anil3a 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

This comment has been minimized.

Copy link

@ayasuda2OO3 ayasuda2OO3 commented Nov 17, 2013

nice structure.

@ethanmuller

This comment has been minimized.

Copy link

@ethanmuller ethanmuller commented Nov 22, 2013

This helped me out. Thanks for posting this! 🍺

@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Nov 26, 2013

that's just awesome !
helped a lot

@fatchat

This comment has been minimized.

Copy link

@fatchat fatchat commented Dec 8, 2013

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

@tony-kerz

This comment has been minimized.

Copy link

@tony-kerz tony-kerz commented Dec 10, 2013

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

This comment has been minimized.

Copy link

@melbourne2991 melbourne2991 commented Jan 31, 2014

friggin awesome cheers!

@ohadperry

This comment has been minimized.

Copy link

@ohadperry ohadperry commented Feb 19, 2014

great!

@ADelRosarioH

This comment has been minimized.

Copy link

@ADelRosarioH ADelRosarioH commented May 13, 2014

THANKS!!!

@m00s

This comment has been minimized.

Copy link

@m00s m00s commented Jul 18, 2014

Really helpful! Thanks

@maisnamraju

This comment has been minimized.

Copy link

@maisnamraju maisnamraju commented Jul 30, 2014

Much Thanks for this.

@suminsudhi

This comment has been minimized.

Copy link

@suminsudhi suminsudhi commented Jul 31, 2014

Thanks a lot. Was very helpful 👍

@gkoberger

This comment has been minimized.

Copy link

@gkoberger gkoberger commented Aug 2, 2014

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

This comment has been minimized.

Copy link

@elrrrrrrr elrrrrrrr commented Aug 17, 2014

Good !

@bubakazouba

This comment has been minimized.

Copy link

@bubakazouba bubakazouba commented Jan 3, 2016

thank you

@alexlebed

This comment has been minimized.

Copy link

@alexlebed alexlebed commented Jan 23, 2016

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

@macdonjo

This comment has been minimized.

Copy link

@macdonjo macdonjo commented Apr 4, 2016

What exactly is body in req.body?

@ltouro

This comment has been minimized.

Copy link

@ltouro 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

This comment has been minimized.

Copy link

@MarcusFleck MarcusFleck commented Aug 31, 2016

Thanks, thats exactly what i was looking for

@yvanwangl

This comment has been minimized.

Copy link

@yvanwangl yvanwangl commented Nov 10, 2016

Thank you. This demo help me a lot !

@Karthik248

This comment has been minimized.

Copy link

@Karthik248 Karthik248 commented Nov 26, 2016

Great demo as a starting point. Thanks.

@c0d0g3n

This comment has been minimized.

Copy link

@c0d0g3n 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

This comment has been minimized.

Copy link

@awhitehouse104 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

This comment has been minimized.

Copy link

@lgutie16 lgutie16 commented Aug 12, 2018

Thank you! you are the best!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.