iv been trying to add post action to add tasks to db , Im using mongoDB as a db.
Here is my User model:
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);
And here is my Task model:
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);
And here is adminController, im getting the error inside 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('/');
})
}
brute test:
addNewTask is working when iv replaced the req.user._id with the _id that appears inside the user in mongodb
so i dont really know why it cant see the _id inside the User scheme
If you any further information please let me know
req.usercoming from? Please post the code that shows how you are adding auserobject to thereqobject.