来自Passport的未定义<LocalStrategy的Node.js>'findOne'

时间:2019-04-26 03:09:21

标签: node.js mongodb mongoose

我使用Passport创建登录名。

但是,我得到了

  

TypeError:无法读取未定义的属性'findOne'

尝试登录时。

调试后,我确认localStrategy.js异步后用户未定义。

我认为所有动作都是完美的,但是我的代码有问题。

我能告诉你我哪里做错了吗?

passport / index.js

const local = require('./localStrategy');
const { User } = require('../model/user');

module.exports = (passport) => {
  passport.serializeUser((user, done) => {
    done(null, user._id);
  });

  passport.deserializeUser((id, done) => {
    User.findOne({ id: id })
      .then((user) => done(null, user))
      .catch((err) => done(err));
  });

  local(passport);
};

passport / localStrategy.js

const LocalStrategy = require('passport-local').Strategy;
const { User } = require('../model/user');

module.exports = (passport) => {
  passport.use(
    new LocalStrategy(
      {
        usernameField: 'email',
        passwordField: 'password'
      },
      async (email, password, done) => {
        try {
          const exUser = await User.findOne({ email: email });
          if (exUser) {
            const result = await bcrypt.compare(password, exUser.password);
            if (result) {
              done(null, exUser);
            } else {
              done(null, false, { message: 'failed.' });
            }
          } else {
            done(null, false, { message: 'failed.' });
          }
        } catch (err) {
          console.error(err);
          done(err);
        }
      }
    )
  );
};

routes / user.js

const express = require('express');
const router = express.Router();

const { isLoggedIn, isNotLoggedIn } = require('./middleware');

const usersController = require('../controller/users_controller');

router.get('/login', isNotLoggedIn, usersController.user_login);

controller / users_controller.js

const User = require('../model/user');
const bcrypt = require('bcrypt');
const passport = require('passport');

exports.user_login = (req, res, next) => {
  passport.authenticate('local', (authError, user, info) => {
    if (authError) {
      console.error(authError);
      return next(authError);
    }
    if (!user) {
      return res.send("not user.")
    }
    return req.login(user, (loginError) => {
      if (loginError) {
        console.error(loginError);
        return next(loginError);
      }
      return res.send("login successfully")
    });
  })(req, res, next);
};

模型/user.js

const mongoose = require('mongoose');

let UserSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    require: true
  },
  createAt: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('User', UserSchema);

2 个答案:

答案 0 :(得分:2)

const { User } = require('../model/user');

此代码返回User = undefined

您可以在'../model/user'中显示代码吗?

您要导出以下内容吗?

module.exports = {
    User: your_user
}

如果您使用:

module.exports = User;

您应该致电

const User = require('../model/user');

代替:

const { User } = require('../model/user');

或者您可以在'../model/user'中更改导出:

module.exports = {
    User: your_user
}

答案 1 :(得分:0)

在查询中应为_id而不是id 护照/index.js

 User.findOne({ _id: id })
      .then((user) => done(null, user))
      .catch((err) => done(err));
  });

在护照/ localStrategy文件中正确导入模型

const User = require('../model/user');