Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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


I'm using Mongoose (on node) and I'm trying to add some additional fields to a model on save by using Mongoose middleware.

I'm taking the often-used case of wanting to add a lastmodifiedsince-date. However, I also want to automatically add the name/profilelink of the user which has done the save.

schema.pre('save', function (next) {; //how to get to 'req'?
  this.lasteditdate = new Date();

I'm using passport - - which results in req.user being present, req of course being the http-request.



I've defined pre on an embedded schema, while I'm calling save on that parent of the embedded instance. The solution posted below (passing arg as the first param of save) works on the non-embedded case, but not on mine.

Problem courtesy of: Geert-Jan


You can pass data to your call which will then be passed to your middleware.

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

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

Unfortunately this doesn't work on embedded schemas today (see 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) {

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

Solution courtesy of: Bill


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription