我已经设置了本地策略,以将用户的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 ,存储在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转换为模型实例吗?