You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Passport.js本地登录策略时user.password返回undefined问题咨询

解决Passport.js LocalStrategy中user.password返回undefined的问题

我来帮你搞定这个让人困惑的问题!你遇到的情况很典型——明明console.log(user)能看到password字段,但直接访问user.password却拿不到值,大概率是Mongoose的字段默认隐藏设置在搞鬼,下面是具体的排查和解决步骤:

最可能的原因:Mongoose Schema隐藏了password字段

如果你的UserModel对应的Mongoose Schema中,password字段设置了select: false,那么默认情况下查询返回的文档对象不会暴露这个字段给直接访问——虽然console.log会把文档对象的所有字段都打印出来,但实际访问user.password时会返回undefined。

举个例子,你的Schema可能是这样的:

const userSchema = new mongoose.Schema({
  email: String,
  password: {
    type: String,
    select: false // 这个配置会让password默认不被查询返回
  },
  // 其他字段...
});

解决方法:显式指定查询时获取password字段

在findOne查询链中添加.select('+password'),强制Mongoose返回password字段:

passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, function(username, password, cb) { 
  'use strict'; 
  UserModel.findOne({ email: username })
    .select('+password') // 加上这一行,显式获取password字段
    .populate('organisation')
    .exec(function(err, user) { 
      if (err) { return cb(err); } 
      console.log(user); 
      if (!user) { return cb(null, false, { message: 'Incorrect email.' }); } 
      console.log(user.password); // 现在就能正常拿到密码哈希值了
      if (!bcrypt.compareSync(password, user.password)) { 
        console.log('password incorrect'); 
        return cb(null, false, { message: 'Incorrect password.' }); // 顺便修正你原代码里的拼写错误:passowrd → password
      } 
      return cb(null, user); 
    }); 
}));

额外验证方法:转成普通JS对象确认

如果还是不确定,可以把Mongoose文档对象转成普通JavaScript对象再查看:

console.log(user.toObject().password);

如果这行能输出密码哈希,那就坐实了是select: false的问题,用上面的方法解决即可。

内容的提问来源于stack exchange,提问作者tmkiernan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:47:43