mongodb TypeError:无法读取undefined的属性(阅读“_id”)

ef1yzkbh  于 2023-08-04  发布在  Go
关注(0)|答案(5)|浏览(127)

我正在做一个个人项目,我真的需要一些帮助
我有这个错误,我不明白为什么:(
下面是我的代码:

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

字符串
在我尝试向数据库添加新帖子之前,一切都运行得很好
这是导致错误的代码部分:

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;


有人能帮帮我吗?

krugob8w

krugob8w1#

错误是因为在这里:

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

字符串
你试图访问“user._id”,但是user里面没有“_id”,所以检查一下user里面有什么。

wlp8pajw

wlp8pajw2#

毫不夸张地说,它就是它所说的那样
无法读取undefined的属性(阅读“_id”)
这意味着req.user(req对象中的对象user)中没有_id属性。看起来你没有发送_id(也许你的负载使用的是id而不是_id?)你能和我们分享你的载荷吗?

tez616oj

tez616oj3#

看起来好像req.user是未定义的,这就是它给你那个错误的原因。试着找出你从哪里得到你的身份证!:)

a8jjtwal

a8jjtwal4#

这里是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;

字符串

2cmtqfgy

2cmtqfgy5#

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

字符串
而不是将"userId"设置为req.user._id,设置为“_id

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


您可能还希望使用.findOne()而不是

.find()


相关问题