节点/猫鼬:在猫鼬中间件中进入请求上下文 [英] node / mongoose: getting to request-context in mongoose middleware

查看:70
本文介绍了节点/猫鼬:在猫鼬中间件中进入请求上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mongoose(在节点上),并且试图通过使用Mongoose中间件在保存时向模型添加一些其他字段.

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

我正在考虑要添加lastmodifiedsince-date的常用情况. 但是,我还想自动添加完成保存的用户的名称/配置文件链接.

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

我正在使用护照- http://passportjs.org/-这导致req.user存在,req当然是http请求.

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

谢谢

编辑

我已经在嵌入式模式中定义了pre,而我正在嵌入式实例的该父实例上调用save.下面发布的解决方案(将arg作为保存的第一个参数)适用于非嵌入式案例,但不适用于我的案例.

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.

推荐答案

您可以将数据传递给Model.save()调用,然后将其传递给中间件.

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

不幸的是,今天这不适用于嵌入式模式(请参见 https://github.com/LearnBoost/猫鼬/问题/838 ).一种解决方法是将属性附加到父项,然后在嵌入式文档中访问它:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆