首页 > 解决方案 > 将 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 转换为模型实例的猫鼬函数?

标签: node.jsexpressmongoosejwtpassport.js

解决方案


推荐阅读