Node / mongoose: getting context request in mongoose middleware

I am using mongoose (on node) and I am trying to add some extra fields to the model for saving using Mongoose middleware.

I take a commonly used case to add a lastmodifiedsince date. However, I also want to automatically add the name / profile for the user who performed the save.

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

I use a passport - http://passportjs.org/ - as a result, req.user is present req, of course, which is an http request.

thank

EDIT

pre , save . , ( arg ), , .

+3
2

Model.save(), .

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

, (. https://github.com/LearnBoost/mongoose/issues/838). , , :

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

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

, , .

+9

, , , , . -

findOneAndUpdate({ '_id': id }, model, { **upsert: true, new: true, customUserId: userId, ipAddress: ipaddress.clientIp** }, function (err, objPersonnel) {

, :

schema.pre('findOneAndUpdate', function (next) {
   // this.options.customUserId,
   // this.options.ipAddress
});

,

+1

All Articles