项目验证失败:任务:对于路径中的值“[]\”(类型字符串),转换为[未定义]失败

问题描述 投票:0回答:1

我一直在开发项目管理工具。我为该项目创建了一个猫鼬模式。但是当我使用 Postman 测试它时,它会抛出错误。我几乎尝试了所有方法并花了几个小时进行调试,但一切都是徒劳的。这是确切的错误:

Project validation failed: tasks: Cast to [undefined] failed for value \"[]\" (type string) at path \"tasks.0\" because of \"TypeError\

我几乎尝试了一切。也许我错过了一些东西,但我花了几个小时,但对我来说没有任何结果。 1.当我删除协作者和任务数组时,它工作正常 2.我直接在这个文件中使用和定义模式,如下所示:

tasks: [taskSchema]
但那次我遇到了另一个错误
cannot read properties of undefined (reading 'length') mongoose

请帮助我如何摆脱这些错误。我使用的是猫鼬版本^8.3.2.

以下是我的文件:

项目.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;
};````
node.js mongodb express mongoose
1个回答
0
投票

它的错误似乎是您的架构中如何定义

collaborators
数组可能存在问题。协作者数组错误地嵌套在另一个数组中。

无法读取未定义的属性(读取“长度”)猫鼬

collaborators: [
      {
        user: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User',
        },
        permissions: {
          type: String,
          enum: ['read', 'write', 'admin'],
          default: 'read',
        },
      },
    ],

现在您的模式应该正确定义数组。

© www.soinside.com 2019 - 2024. All rights reserved.