skip to Main Content

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?

4

Answers


  1. Chosen as BEST ANSWER

    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;
    

  2. 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.

    Login or Signup to reply.
  3. 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?

    Login or Signup to reply.
  4. 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! 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search