Mongoose将req对象传递给中间件 [英] Mongoose pass req object to middleware

查看:79
本文介绍了Mongoose将req对象传递给中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为mongoose编写一个中间件,使用pre query hook为每个查找对象执行。

I am writing a middleware for mongoose that gets executed for every find object using pre query hook.

postSchema.pre('query', function(query, next) {
// I want to access the req.user object here
    query.populate('Category');
    next();
});

我想访问pre中的req.user对象,以便为api服务器发出每个请求。如何将对象传递给中间件?

I want to access req.user object inside the pre for every request made to the api server. How can i pass the object to the middleware?

是否可能?

https://github.com/Automattic/mongoose/issues/1931

我发现了上述内容,但它没有谈论传递req对象。

I found the above but it doesnt talk about passing req object.

=============== =====

====================

在对这个问题感到困惑后编辑。

Edit after some confusion about the question.

我想要完成的是获取req.user角色,模型名称将其传递给另一个函数以获取查询的查询条件。因此,根据用户角色和访问的模型类型,查询条件将发生变化。

What i am trying to accomplish is to get the req.user role and the model name pass it to another function to get the query condition for find. So depending on the user role and the type of model accessed the query condition will change.

推荐答案

将中间件包装在另一个中间件中可以访问 req

Wrap the middleware in another middleware that has access to req.

有点像假设快递

router.verb('/some-route', function (req, res, next) {
   postSchema.pre('query', function(query, next) {
      console.log(req);
      query.populate('Category');
      next();
   });
});

编辑
- 仅将此附加到您的路线希望预备。

Edit - Attach this only to the route that you want the prehook for.

免责声明 - 未经测试。

这篇关于Mongoose将req对象传递给中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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