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

};
  

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

  1. Access the model from request object in our routes
  
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);
      
});
  
});
  
  1. In your app.js file add the middleware
  
var db = require('./mods/db.js');
  
app.use(db());
  

Just make sure to add this middleware above your routes.

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

excellence-social-linkdin
excellence-social-facebook
excellence-social-instagram
excellence-social-skype