首页 > 解决方案 > 在 NodeJS 如何从 Mongoose 虚拟访问请求标头?

问题描述

我正在使用 NodeJS 创建 REST API。在 Mongoose 的帮助下,我正在与后端进行交互。我在下面写了 virtual 来为每个“查找”调用执行一些操作。

commentSchema.virtual('userLiked', {
  ref: 'CommentReaction',
  localField: '_id',
  foreignField: 'commentId',
  options: {
    match: doc => {
      const token = req.headers.authorization.split(' ')[1];
      const decodedToken = jwt.verify(token, process.env.JWT_KEY);
      return { creator: decodedToken.userId }
    }
  },
  count: true
});

在上面的代码中,我试图访问请求标头以获取用户 ID 并执行一些操作。如何在 Mongoose 中访问来自虚拟的请求?

标签: node.jsexpressmongoose

解决方案


我可以使用localStorage npm 解决问题。
使用它,在请求可用的控制器功能中,我在 localStorage 中设置“授权”,如下面的代码:

exports.fetchCommentsForNews = (req, res, next) => {
  if (req.headers.authorization != null) {
    localStorage.setItem('auth', req.headers.authorization);
  } else {
    localStorage.setItem('auth', '');
  }
  .
  .
  .
}

在模式的虚拟代码中,我从 localStorage 获取身份验证,如下所示:

commentSchema.virtual('userLikedCount', {
  ref: 'CommentReaction',
  localField: '_id',
  foreignField: 'commentId',
  options: {
    match: doc => {
      let userId = -1;
      let auth = localStorage.getItem('auth');
      if (auth != '') {
        const decodedToken = Util.decodeToken(auth);
        userId = decodedToken.userId;
      }

      return { creator: userId }
    }
  },
  count: true
});


推荐阅读