HomeBack-End & DatabaseGetting Started With Express 4.x – MongoDB – Tutorial 8

Getting Started With Express 4.x – MongoDB – Tutorial 8

In this blog post we will see how to interact with mongodb in express. We will use the mongoose module for this.

Basic working on mongoose has already been discussed here, so i won’t be covering that part again. I will show here what is correct way to integrate mongoose with expressjs.

We will create a custom middleware and insert mongoose scheme into the request object and then easily use it in all our routes. See blog post here on how to create a custom middleware

So here are steps to follow
1. Create a new folder mods/ in your site root and a db.js file to it

[js]
// the middleware function
module.exports = function () {
var mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://127.0.0.1/obi’);

var conn = mongoose.connection;

// incase you need gridfs
//var Grid = require(‘gridfs-stream’);
//Grid.mongo = mongoose.mongo;
//var gfs = Grid(conn.db);

var model_schema = mongoose.Schema({}, {
strict: false,
collection: ‘collection_name’
});
var CollectionModel = conn.model(‘collection_name’, model_schema);

conn.on(‘error’, function (err) {
console.log(err);
process.exit();
})
return function (req, res, next) {
req.mongo = conn;
//req.gfs = gfs;
req.Collection = CollectionModel;
next();
}

};
[/js]

In the above code we have added CollectionModel to the req variable. We can similarly add multiple schema to the request object.

2. Access the model from request object in our routes

[js]
var express = require(‘express’);
var router = express.Router();
var mongoose = require(‘mongoose’);

router.get(‘/list’, function (req, res) {
var Collection = req.Collection;
Collection.find().lean().exec(function(err,result){
res.json(result);
});
});
[/js]

3. In your app.js file add the middleware

[js]
var db = require(‘./mods/db.js’);
app.use(db());
[/js]

Just make sure to add this middleware above your routes.

So above is a clean and modular way to integrate mongoose with express.

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: