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 commented Jul 19, 2011

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

@david-truong

This comment has been minimized.

Copy link

david-truong commented Feb 2, 2012

Great example, thanks!

@dfucci

This comment has been minimized.

Copy link

dfucci commented Mar 7, 2012

Thanks man, very helpful!

@tjeastmond

This comment has been minimized.

Copy link

tjeastmond commented Apr 6, 2012

Perfect. Thank you for this

@bhurlow

This comment has been minimized.

Copy link

bhurlow commented Apr 13, 2012

yea this is a great simple example. thnx!

@y0j

This comment has been minimized.

Copy link

y0j commented Jun 6, 2012

thank you!

@elemenofi

This comment has been minimized.

Copy link

elemenofi commented Aug 9, 2012

LOVE!

@ultra2

This comment has been minimized.

Copy link

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 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 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 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 commented Jan 13, 2013

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

@coughski

This comment has been minimized.

Copy link

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 commented Mar 8, 2013

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

@pdarkness

This comment has been minimized.

Copy link

pdarkness commented Mar 15, 2013

thanks =)

@aisipos

This comment has been minimized.

Copy link

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 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 commented Aug 2, 2013

Great example to me as a beginner : -]

@aymen-mouelhi

This comment has been minimized.

Copy link

aymen-mouelhi commented Aug 7, 2013

thank you !

@balaclark

This comment has been minimized.

Copy link

balaclark commented Aug 16, 2013

Good stuff, thanks.

@takecian

This comment has been minimized.

Copy link

takecian commented Aug 25, 2013

thanks!

@adriancooney

This comment has been minimized.

Copy link

adriancooney commented Aug 25, 2013

Thanks!

@djmccormick

This comment has been minimized.

Copy link

djmccormick commented Sep 17, 2013

Thank you!

@mattjburrows

This comment has been minimized.

Copy link

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 commented Sep 27, 2013

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

@Deacs

This comment has been minimized.

Copy link

Deacs commented Oct 8, 2013

Thanks!

@anil3a

This comment has been minimized.

Copy link

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.

@ayasuda2003

This comment has been minimized.

Copy link

ayasuda2003 commented Nov 17, 2013

nice structure.

@ethanmuller

This comment has been minimized.

Copy link

ethanmuller commented Nov 22, 2013

This helped me out. Thanks for posting this! 🍺

@ghost

This comment has been minimized.

Copy link

ghost commented Nov 26, 2013

that's just awesome !
helped a lot

@fatchat

This comment has been minimized.

Copy link

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 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 commented Jan 31, 2014

friggin awesome cheers!

@ohadperry

This comment has been minimized.

Copy link

ohadperry commented Feb 19, 2014

great!

@ADelRosarioH

This comment has been minimized.

Copy link

ADelRosarioH commented May 13, 2014

THANKS!!!

@m00s

This comment has been minimized.

Copy link

m00s commented Jul 18, 2014

Really helpful! Thanks

@maisnamraju

This comment has been minimized.

Copy link

maisnamraju commented Jul 30, 2014

Much Thanks for this.

@suminsudhi

This comment has been minimized.

Copy link

suminsudhi commented Jul 31, 2014

Thanks a lot. Was very helpful 👍

@gkoberger

This comment has been minimized.

Copy link

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 commented Aug 17, 2014

Good !

@bubakazouba

This comment has been minimized.

Copy link

bubakazouba commented Jan 3, 2016

thank you

@alexlebed

This comment has been minimized.

Copy link

alexlebed commented Jan 23, 2016

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

@macdonjo

This comment has been minimized.

Copy link

macdonjo commented Apr 4, 2016

What exactly is body in req.body?

@ltouro

This comment has been minimized.

Copy link

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 commented Aug 31, 2016

Thanks, thats exactly what i was looking for

@yvanwangl

This comment has been minimized.

Copy link

yvanwangl commented Nov 10, 2016

Thank you. This demo help me a lot !

@Karthik248

This comment has been minimized.

Copy link

Karthik248 commented Nov 26, 2016

Great demo as a starting point. Thanks.

@c0d0g3n

This comment has been minimized.

Copy link

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 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 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.