I have been working on a project management tool. I created a mongoose schema for the Project. But when I test it using Postman it throws an error. I tried almost everything and spent hours debugging but all in vain. Here is the exact error:
Project validation failed: tasks: Cast to [undefined] failed for value "[]" (type string) at path "tasks.0" because of "TypeError
I have tried almost everything. May be I missed something but i spent hours but nothing worked out for me. 1. When I removed both collaborators and tasks array it worked fine
2. I have used and define schema directly in this file like this:
tasks: [taskSchema]
but that time i encounter another error
cannot read properties of undefined (reading 'length') mongoose
Please help me how can i get a away with these errors. I am using mongoose version ^8.3.2.
Below are my files:
Project.model.js:
const projectSchema = mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
collaborators: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
permissions: {
type: String,
enum: ['read', 'write', 'admin'],
default: 'read',
},
],
tasks: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Task',
},
],
},
{
timestamps: true,
},
);
const Project = mongoose.model('Project', projectSchema);
module.exports = Project;
project.controller.js:
const createProject = catchAsync(async (req, res) => {
const project = await projectService.createProject(req.body, req.user.id);
res.status(httpStatus.CREATED).json(project);
});
services.js:
const createProject = async (projectBody, userId) => {
const project = await Project.create({ ...projectBody, user: userId });
return project;
};````