无法使用mongoDB读取undefined(阅读“_id”)的属性

s3fp2yjn  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(155)

iv一直在尝试添加post操作来将任务添加到db,Im使用mongoDB作为db。
以下是我的用户模型:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
    username: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    }
})

module.exports = mongoose.model('User', userSchema);

字符串
下面是我的任务模型:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const taskScheme = new Schema({
    description: {
        type: String,
        required: true
    },

    status: {
        type: String,
        required: true
    },

    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    }
})

module.exports = mongoose.model('Task', taskScheme);


这里是adminController,我得到了addNewTask内的错误

const Task = require("../models/task");

exports.addNewTask = (req, res, next) => {
    const taskDesc = req.body.taskDesc;
    const userId = req.user._id;
    console.log('taskDesc is: ', taskDesc);
    console.log('req.user is: ', req.user) // Output: 'req.user is:  undefined' 
    
    const newTask = new Task(
        {
        description: taskDesc,
        status: 'In Progress',
        userId: userId //get somehow userId , but need first maybe to validate and when moving to all tasks page
        }
    );

    newTask.save()
        .then(() => {
            console.log('Task created');
            res.redirect('/');
        })
        .catch((err) => {
            console.log(err);
        })
}

//TODO: +add: check what user is connected and than deleted the task with the correct userid to match the id in the db
exports.removeTask = (req, res, next) => {
    const taskId = req.body.taskId;

    Task.findByIdAndRemove({
        _id: taskId
    })
        .then(() => {
            res.redirect('/')
        })
        .catch(err => {
            console.log('removeTask error: ', err);
        });
}
//TODO: same things as i wrote in removeTask
exports.editTaskToFinish = (req, res, next) => {
    const taskId = req.body.taskId;
    Task.findByIdAndUpdate(
        {_id: taskId},
        {$set: {status: 'Done'}})
        .then(() => {
            res.redirect('/');
        })
        .catch((err) => {
            console.log('editTaskToFinish: ', err)
            res.redirect('/');
        })
}


蛮力测试:
当iv将req.user._id替换为mongodb中出现在用户内部的_id时,addNewTask正在工作
所以我真的不知道为什么它不能看到用户方案中的_id
如果你有任何进一步的信息,请让我知道

jutyujz0

jutyujz01#

我不知道为什么,但改变了路线:

req.user._id

字符串

req.session.user._id


做了这件工作

相关问题