I'm doing a task application with node.js, express and mongoDB, the fact is that I'm trying to use my data from my model called User in my model called Task, my schema User has a field called tasks which is an array where all the tasks go, then when creating a task, I want to show the user's _id and this is what it tells me:
TypeError: Cannot read property '_id' of undefined (en el controlador del task que esta adjuntado abajo)
This is my code:
Models: Task
let taskSchema = new Schema({
description: {
type: String,
required: [true, 'The description of the task is obligatory'],
unique: true
},
completed: {
type: Boolean,
required: false,
default: false
},
user: {
type: Schema.Types.ObjectId,
ref: 'User'
}
});'
User Model:
let userSchema = new Schema({
name: {
type: String,
required: [true, "The name is obligatory"]
},
email: {
type: String,
required: [true, "The email is obligatory"],
unique: true
},
password: {
type: String,
required: [true, "The password is obligatory"]
},
identification: {
type: String,
required: [true, "The identification is obligatory"],
unique: true
},
role: {
type: String,
enum: validRoles,
required: false,
default: "USER"
},
online: {
type: Boolean,
default: false
},
birthday: {
type: Date,
required: false,
},
tasks: {
type: Array,
required: false,
default: []
}
});
Task Controller:
let body = req.body;
let task = new Task({
(ACA ESTA EL ERROR!)user: req.user._id,
description: body.description,
completed: body.completed
});
task.save((err, task) => {
if (err) {
return res.status(500).json({
ok: false,
err
});
}
res.json({
ok: true,
task,
userUpdated
});
});
If you can help me, it would be very helpful, thank you very much!