Tuesday, November 1, 2011

Mongoose and MongoHQ


A while ago I wrote a post about how to hook up node.js with the MongoHQ database hosting service. I still love MongoHQ, but my mongo wrapper around the node mongodb native driver sucked! I recently switched wereviewutah.com over to use Mongoose and just wanted to share with everyone how easy it is to use Mongoose with MongoHQ.

Sample Model File (models.js)
var db = require('./config/db')
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var Review = new Schema({
article : String
, count : Number
, date : { type: Date, default: Date.now }
, images : [String]
, industry : String
, location : {
city : String
, state : String
, zip : String
, address : String
}
, rating : String
, slug : String
, snippet : String
, tags : [String]
, title : String
, url : String
})
mongoose.connect('mongodb://' + db.user + ':' + db.pass + '@' + db.host + ':' + db.port + '/' + db.name)
mongoose.model('Review', Review)
view raw models.js hosted with ❤ by GitHub


Sample Config File (./config/db.js)
module.exports = {
user: "username",
pass: "password",
name: "yourdatabase",
host: "Flame.mongohq.com",
port: 27094
}
view raw db.js hosted with ❤ by GitHub


Sample Route File (server.js)
var models = require('./models')
var mongoose = require('mongoose')
var Review = mongoose.model('Review')
var express = require('express')
var app = express.createServer()
// ... other requires
// ... config stuff
// simple route to get a paginated page by number
// We use Mongoose to find all the Reviews, with certain fields
// skipped, limited and sorted for pagination
app.get('/pages/:page', pagination, function(req, res) {
var page = req.param("page") || 1
Review.find({}, {'slug':1,'snippet':1,'images':1,'date':1,'title':1,'location':1,'rating':1}, {skip: (page - 1) * limit, limit: limit, sort: [['date','desc']]}, function(err, reviews) {
if (err) return res.send(err)
res.render('home.html', {
reviews: reviews
})
})
})
// Review.collection.findAndModify accesses the MongoDB native wrapper
// and requires converting the id to an objectId. Review.find() calls
// do that through mongoose
app.get('/reviews/:reviewId', function(req, res) {
var reviewId = req.param("reviewId")
Review.collection.findAndModify({_id: new ObjectId(reviewId)}, [], {$inc:{count:1}}, function(err, review) {
res.render('view.html', {review: review});
});
});
app.listen(80)
view raw sample-route.js hosted with ❤ by GitHub

2 comments: