TypeError:无法读取未定义的bcryptjs会话的属性“ _id”

时间:2019-06-10 18:00:16

标签: javascript node.js mongodb undefined id

我当前正在为我的项目实现身份验证部分,问题是当我完成尝试为身份验证实现的代码时,出现此错误 TypeError:无法读取未定义的属性“ _id”

我不知道该怎么办,我知道该用户是未定义的,但我不知道下一步是什么,我基本上被困住了,如果您可以看一下代码,我将不胜感激。尝试看看它如何解决。 我在auth控制器btw中使用bcryptjs,但我希望这段代码足以看到正在发生的事情,甚至可以解决它。

require('dotenv').config({path: "node.env"});
const path = require('path');
const express = require('express');

const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const flash = require("connect-flash");

const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const errorController = require('./controllers/error');

const mongodb_uri = process.env.MONGODB_URI;
const app = express();
const csrf = require("csurf");
const User = require("./models/user");

const store = new MongoDBStore({
    uri: mongodb_uri,
    collection: "sessions"
});

const csrfProtection = csrf();


app.set('view engine', 'ejs');
app.set('views', 'views');

const adminRoutes = require("./routes/admin");
const blogRoutes = require("./routes/blog");
const authRoutes = require("./routes/auth");


app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(express.static(path.join(__dirname, 'public')));


app.use(
    session({
        secret: process.env.SECRET,
        cookie: {
            maxAge: 1000 * 60 * 60 * 24 * 7
        },
        store: store,
        resave: false,
        saveUninitialized: false,

    })
)

app.use(flash());
app.use(csrfProtection);

app.use((req, res, next) => {
    if (!req.session.user._id) {
        return next();
    }
    User.findById(req.session.user._id)
    .then(user => {
        req.user = user;
        next();
    })
    .catch(err => console.log(err));
})

app.use((req, res, next) => {
    res.locals.isauthenticated = req.session.isLoggedIn;
    res.locals.csrfToken = req.csrfToken();
    next();
});

app.use("/admin", adminRoutes);
app.use(blogRoutes);


app.use(errorController.get404);

mongoose.set('useCreateIndex', true);

mongoose.connect(mongodb_uri, {
    useNewUrlParser: true
});

app.listen(3000, function () {
    console.log("listening to port 3000")
})

我希望一切正常,我不太明白问题出在哪里,我什至遵循了课程讲师的结构。

1 个答案:

答案 0 :(得分:0)

您的代码:

app.use((req, res, next) => {
   if (!req.session.user._id) {
       return next();
   }
   User.findById(req.session.user._id)
   .then(user => {
       req.user = user;
       next();
   })
   .catch(err => console.log(err));
})

您实际上打算做什么:


app.use((req, res, next) => {
  if (!req.session.user) {
    return next();
  }
  User.findById(req.session.user._id)
    .then(user => {
      if (!user) {
        return next();
      }
      req.user = user;
      next();
    })
    .catch(err => console.log(err));
});

您必须先检查req.session.user(删除._id)。
然后您忘了签入.then(user => {...})再次寻找user
即:
 if(!user){return next();}