node / mongoose: getting to request-context in mongoose middleware

You can pass data to your Model.save() call which will then be passed to your middleware.

// in your route/controller
var item = new Item();
item.save(req, function() { /*a callback is required when passing args*/ });

// in your model
item.pre('save', function (next, req, callback) {
  console.log(req);
  next(callback);
});

Unfortunately this doesn't work on embedded schemas today (see https://github.com/LearnBoost/mongoose/issues/838). One work around was to attach the property to the parent and then access it within the embedded document:

a = new newModel;
a._saveArg = 'hack';

embedded.pre('save', function (next) {
  console.log(this.parent._saveArg);
  next();
})

If you really need this feature, I would recommend you re-open the issue that I linked to above.


It can be done with 'request-context'. Step to do:

Install request-context

npm i request-context --save

In your app/server init file:

var express = require('express'),
app = express();
//You awesome code ...
const contextService = require('request-context');
app.use(contextService.middleware('request'));
//Add the middleware 
app.all('*', function(req, res, next) {
  contextService.set('request.req', req);
  next();
})

In you mongoose model:

const contextService = require('request-context');
//Your model define
schema.pre('save', function (next) {
  req = contextService.get('request.req');
  // your awesome code
  next()
})