node.js - 在 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 中访问来自虚拟的请求?
解决方案
我可以使用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
});
推荐阅读
- swift - Swift 4 / Xcode 10 错误消息:非法 NSOutlineView 数据源
- arrays - 如何在 Angular 8 中合并 2 个 JSON 文件
- amazon-web-services - 将 DocumentDB 与 SNS 主题连接,无需中间件
- azure-cloud-shell - 通过 Azure cloudshell 设置的标签不会出现在门户中
- python - 即使可以使用 pip list 看到包,也找不到包
- python - 在 for 循环中使用三元条件添加新列
- kernel-module - 带有系统调用的 AIX 内核扩展
- c# - ASP.NET Core 2.2 如何覆盖 UserManager.CreateAsync 以删除唯一的用户名要求
- php - mysqli连接文件不识别准备干
- windows - 查找带有时间戳的文件夹时,我可以在 CMD 中使用通配符吗?