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
如果你有任何进一步的信息,请让我知道
1条答案
按热度按时间jutyujz01#
我不知道为什么,但改变了路线:
字符串
到
型
做了这件工作