如何修复“TypeError:无法读取未定义的属性‘id’”错误?

时间:2021-03-04 12:49:59

标签: javascript node.js mongodb express mongoose

我正在开发一个应用程序,该应用程序使用数据库并使用用户 ID(即其用户名)向用户添加项目,但是当我尝试添加项目时出现错误,我似乎无法弄清楚如何修理它。这是错误:

TypeError: Cannot read property 'id' of undefined
    at C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\app.js:118:26
    at Layer.handle [as handle_request] (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\router\index.js:275:10)
    at SessionStrategy.strategy.pass (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\passport\lib\middleware\authenticate.js:343:9)
    at SessionStrategy.authenticate (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\passport\lib\strategies\session.js:75:10)
    at attempt (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\passport\lib\middleware\authenticate.js:366:16)
    at authenticate (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\passport\lib\middleware\authenticate.js:367:7)
    at Layer.handle [as handle_request] (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\Children\Desktop\Web Projects\Sermon_Tracker\node_modules\express\lib\router\index.js:335:12)

这里说的是问题所在:

app.post("/workspace", function (req, res) {
    const date = req.body.input1;

    console.log(date);

    //Once the user is authenticated and their session gets saved, their user details are saved to req.user.
    console.log(req.user.id);

    User.findById(req.user.id, function (err, foundUser) {
        if (err) {
            console.log(err);
        } else {
            if (foundUser) {
                foundUser.item = date;
                foundUser.save(function () {
                    res.redirect("/workspace");
                });
            }
        }
    });
});

完整代码如下:

//jshint esversion:6
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require('express-session');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require('mongoose-findorcreate');

const app = express();

const Schema = mongoose.Schema;

app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(session({
    secret: "Our little item.",
    resave: false,
    saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("mongodb://localhost:27017/userDB", { useNewUrlParser: true });
mongoose.set("useCreateIndex", true);

const userSchema = new mongoose.Schema({
    email: String,
    password: String,
    googleId: String,
    items: { type: [Schema.Types.ObjectId], ref: 'Item' }
});

const ItemSchema = new mongoose.Schema({
    date: String,
    loc: String,
    title: String,
    passage: String,
    file: String
});

userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);

const User = new mongoose.model("User", userSchema);
const Item = mongoose.model("Item", ItemSchema);

passport.use(User.createStrategy());

passport.serializeUser(function (user, done) {
    done(null, user.id);
});

passport.deserializeUser(function (id, done) {
    User.findById(id, function (err, user) {
        done(err, user);
    });
});

passport.use(new GoogleStrategy({
    clientID: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
    callbackURL: "http://localhost:3000/auth/google/secrets",
    userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
    function (accessToken, refreshToken, profile, cb) {
        console.log(profile);

        User.findOrCreate({ googleId: profile.id }, function (err, user) {
            return cb(err, user);
        });
    }
));

app.get("/", function (req, res) {
    res.redirect("/home");
});

app.get("/home", function (req, res) {
    res.render("home");
});

app.get("/login", function (req, res) {
    res.render("login");
});

app.get("/signup", function (req, res) {
    res.render("signup");
});

app.get("/workspace", function (req, res) {
    User.find({ "items": { $ne: null } }, function (err, foundUsers) {
        if (err) {
            console.log(err);
        } else {
            if (foundUsers) {
                res.render("workspace", { itemList: foundUsers });
            }
        }
    });
});


app.post("/workspace", function (req, res) {
    const date = req.body.input1;

    console.log(date);

    //Once the user is authenticated and their session gets saved, their user details are saved to req.user.
    console.log(req.user.id);

    User.findById(req.user.id, function (err, foundUser) {
        if (err) {
            console.log(err);
        } else {
            if (foundUser) {
                foundUser.item = date;
                foundUser.save(function () {
                    res.redirect("/workspace");
                });
            }
        }
    });
});

app.get("/logout", function (req, res) {
    req.logout();
    res.redirect("/");
});

app.post("/signup", function (req, res) {

    User.register({ username: req.body.username }, req.body.password, function (err, user) {
        if (err) {
            console.log(err);
            res.redirect("/signup");
        } else {
            passport.authenticate("local")(req, res, function () {
                res.redirect("/workspace");
            });
        }
    });

});

app.post("/login", function (req, res) {

    const user = new User({
        username: req.body.username,
        password: req.body.password
    });

    req.login(user, function (err) {
        if (err) {
            console.log(err);
        } else {
            passport.authenticate("local")(req, res, function () {
                res.redirect("/workspace");
            });
        }
    });

});

app.listen(3000, function () {
    console.log("Server started on port 3000.");
});

我该如何解决?我尝试了多种方法,但都没有奏效。

1 个答案:

答案 0 :(得分:0)

好的,我想出了问题和答案,我把id而不是_id!所以这就是为什么给了我错误!但我仍然有一个问题,如何在项目模式中保存日期?这是foundUser.item = date;,这是代码:

app.post("/workspace", function (req, res) {
    const date = req.body.input1;

    console.log(date);

    //Once the user is authenticated and their session gets saved, their user details are saved to req.user.
    console.log(req.user._id);

    User.findById(req.user._id, function (err, foundUser) {
        if (err) {
            console.log(err);
        } else {
            if (foundUser) {
                foundUser.item = date;
                foundUser.save(function () {
                    res.redirect("/workspace");
                });
            }
        }
    });
});