简体   繁体   中英

TypeError: Cannot read properties of undefined (reading '_id')

I'm working on a personal project and i really need some help

I'm having this error and i don't understand why:(

Here is my code:

 //authRoutes.js


const { Router } = require('express');
const authController = require('../controllers/authController');
const { requireAuth } = require('../middleware/authMiddleware');
var Post = require('../models/post')
const router = Router();


router.use(function(req,res, next){
 res.locals.user = req.user;
next();
});

router.get('/signup', authController.signup_get);
router.post('/signup', authController.signup_post);
router.get('/login', authController.login_get);
router.post('/login', authController.login_post);
router.get('/logout', authController.logout_get);


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


router.get("/about", function (req, res) {
 res.render("about");
});


router.get("/", requireAuth, function(req,res){
 Post.find({userID:req.user._id}).exec(function(err, posts){
  if(err){
   console.log(err);
  }
 res.render("posts",{posts:posts})
})
})

 router.get("/add", requireAuth, function(req,res){
  res.render("addpost")
 })

Everything was working fine until I tried to add a new post to the database

This is the part of the code that's causing the error:

 router.post("/add",requireAuth, function(req,res){


  var newPost = new Post({
   title:req.body.title,
   content:req.body.content,
   userID:req.user._id
  })
  newPost.save(function(err,post){
   if(err){
    console.log(err)
    res.redirect("/posts")
   }
  })
 })




 module.exports = router;

can someone help me?

The error is because in here:

var newPost = new Post({
   title:req.body.title,
   content:req.body.content,
   userID:req.user._id
})

you're trying to access "user._id", but there is not "_id" inside user, so check what is inside user.

Quite literally, it is what it say it is

Cannot read properties of undefined (reading '_id')

This means that there's no _id property inside req.user (the object user inside the req object). It seems you're not sending _id (maybe your payload is using id instead of _id ? Could you share your payload with us?

it seems like req.user is undefined and that is the reason of why it gives you that error. Try to find out where you get your id from: )

Here is user.js

    const mongoose = require('mongoose');
const { isEmail } = require('validator');
const bcrypt = require('bcrypt');

const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: [true, 'Please enter an email'],
    unique: true,
    lowercase: true,
    validate: [isEmail, 'Please enter a valid email']
  },
  password: {   
    type: String,
    required: [true, 'Please enter a password'],
    minlength: [6, 'Minimum password length is 6 characters'],
  }
});


// fire a function before doc saved to db
userSchema.pre('save', async function(next) {
  const salt = await bcrypt.genSalt();
  this.password = await bcrypt.hash(this.password, salt);
  next();
});

// static method to login user
userSchema.statics.login = async function(email, password) {
  const user = await this.findOne({ email });
  if (user) {
    const auth = await bcrypt.compare(password, user.password);
    if (auth) {
      return user;
    }
    throw Error('incorrect password');
  }
  throw Error('incorrect email');
};

const User = mongoose.model('user', userSchema);

module.exports = User;

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