Node.js, express, mongoose.js and modules

I found node.js modules (exports) a little confusing at first.

So, here’s a small example using node.js with mongoose and modules to represent something closer to a real world project structure.

app.js references auctions.js which is basically the controller logic.

auctions.js references ./models/auction.js which holds the model and schema.


var express = require('express');
var mongoose = require('mongoose');

var app = module.exports = express.createServer();


app.configure(function () {

app.get('/', function (req, res) {
    res.send('hello world');

// auctions api
var auctions = require('./auctions.js');
app.get('/auctions', auctions.list);'/auctions/create', auctions.create);



// load up the model
var Auction = require('./models/auction.js');

exports.create = function (req, res) {
    // replace data assigments with something like
    // {comments: req.body.comments}
    new Auction({
        iso_currency_symbol: 'GBP',
        comments: 'second auction'

    res.send('hello, this is response text');

exports.list = function (req, res) {
    Auction.find(function (err, auctions) {


var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var auction_schema = new Schema({
    iso_currency_symbol: String,
    created_date: { type: Date, default: },
    started_date: { type: Date },
    owner_id: ObjectId,
    comments: String

module.exports = mongoose.model('Auction', auction_schema);

Note: I’m not a node.js expert so if there is a better way to do this, lemme know 🙂


3 thoughts on “Node.js, express, mongoose.js and modules

  1. Thanks for sharing your approach on this—I too am working with Mongoose and Express, but had scope issues modularizing it; this is definitely helpful, thanks!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s