node.js - 将 JWT 有效负载转换为 Mongoose 模型实例
问题描述
我已经设置了本地策略以将用户包含user instance
到 JWT 有效负载中,当然是 JSON 格式,如下所示:
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
async function (email, password, done) {
try {
const user = await User.findOne({ email })
const isCorrectPassword = await bcrypt.compare(password, user.password)
if (!user || !isCorrectPassword) {
return done(null, false, { message: "Email o contraseña incorrecto/s" })
}
return done(null, user.toJSON(), { message: "Ingreso existoso"})
} catch (e) {
return done(e)
}
}
))
现在,当我的一个路由调用时passport.authenticate()
,我的 JWT 策略被配置为从有效负载中提取用户的 id,然后查询数据库以便从该 id 取回一个 mongoose 模型实例,并将其存储在req.user
. 像这样:
passport.use(new JWTStrategy({
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET
},
async function(jwtPayload, done) {
try {
const user = await User.findById(jwtPayload._id)
return done(null, user)
} catch (e) {
return done(e)
}
}
))
我觉得查询数据库以获取在有效负载中编码的相同信息的效率非常低,所以我想不这样做const user = await User.findById(jwtPayload._id)
,而是返回有效负载(return done(null, jwtPayload)
),但因为jwtPayload
实际上是 JSON,而不是猫鼬对象,我担心它不会开箱即用。
我怎么能做到这一点?是否有将 JSON 转换为模型实例的猫鼬函数?
解决方案
推荐阅读
- python - 如何从异步多线程中获取顺序结果
- python-3.x - 如何绘制带有虚线轮廓且没有表面颜色的双锥?
- c# - 在前台引入折叠的最小化 wpf 应用程序
- reactjs - 使用 webpack 覆盖 node_modules lib 中的文件
- wordpress - WordPress 联系表 7 - 通过 cookie 数据填写字段
- reactjs - 箭头函数的参数
- mysql - 为什么MYSQL中的循环过程返回错误?
- hide - 是否可以在 wxTreeCtrl 中隐藏 wxTreeItems?
- android - 从 localhost 访问数据。在android中工作,但不在网络浏览器中
- ios - Where to put sqlite .db files in iOS project?