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
Here is user.js
The error is because in here:
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
This means that there’s no
_id
property insidereq.user
(the object user inside the req object).It seems you’re not sending
_id
(maybe your payload is usingid
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! 🙂