如何修复"TypeError: Cannot read property 'id' of undefined"错误?



我正在研究一个使用数据库并使用用户ID为用户添加项目的应用程序,这是它的用户名,但是当我尝试添加一个项目时,我得到一个错误,我似乎无法找出如何修复它。下面是错误:

TypeError: Cannot read property 'id' of undefined
at C:UsersChildrenDesktopWeb ProjectsSermon_Trackerapp.js:118:26
at Layer.handle [as handle_request] (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulesexpresslibrouterlayer.js:95:5)
at next (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulesexpresslibrouterroute.js:137:13)
at Route.dispatch (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulesexpresslibrouterroute.js:112:3)
at Layer.handle [as handle_request] (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulesexpresslibrouterlayer.js:95:5)
at C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulesexpresslibrouterindex.js:281:22
at Function.process_params (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulesexpresslibrouterindex.js:335:12)
at next (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulesexpresslibrouterindex.js:275:10)
at SessionStrategy.strategy.pass (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulespassportlibmiddlewareauthenticate.js:343:9)
at SessionStrategy.authenticate (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulespassportlibstrategiessession.js:75:10)
at attempt (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulespassportlibmiddlewareauthenticate.js:366:16)
at authenticate (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulespassportlibmiddlewareauthenticate.js:367:7)
at Layer.handle [as handle_request] (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulesexpresslibrouterlayer.js:95:5)
at trim_prefix (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulesexpresslibrouterindex.js:317:13)
at C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulesexpresslibrouterindex.js:284:7
at Function.process_params (C:UsersChildrenDesktopWeb ProjectsSermon_Trackernode_modulesexpresslibrouterindex.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.");
});

我该如何修复它?我试了很多方法,但都不起作用。

好了,我找到了问题和答案,我把_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");
});
}
}
});
});

相关内容

最新更新