简体   繁体   中英

How to fix “TypeError: Cannot read property 'id' of undefined” error?

I am working on a app that uses databases and adds items to the user using the user ID which is its username, but when i try to add an item i get an error and i can't seem to figure out how to fix it. Here is the error:

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)

Here is where it is saying the problem is:

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");
                });
            }
        }
    });
});

Here is the full code:

//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.");
});

How can i fix it? I tried multiple things but none of them work.

Ok i figured out the problem and the answer, i had put id instead of _id , So that is why is gave me the error? But i do still have a question, how can i save the date in the item schema? It is this foundUser.item = date; , here is the code:

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");
                });
            }
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM