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.

app.js

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

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

mongoose.connect('mongodb://localhost/marketplace');

app.configure(function () {
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
});

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

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

app.listen(3000);

auctions.js

// 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'
    }).save();

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

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

./models/auction.js

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

var auction_schema = new Schema({
    iso_currency_symbol: String,
    created_date: { type: Date, default: Date.now },
    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 🙂

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s