Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

node.js - 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) {
  this.lasteditby=req.user.name; //how to get to 'req'?
  this.lasteditdate = new Date();
  next()
})

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

Thanks

EDIT

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...