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

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

问题描述

我正在使用 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 作为 save 的第一个参数传递)适用于非嵌入式案例,但不适用于我的.

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天全站免登陆