首页 > 解决方案 > 从 _id 向 mongodb 添加另一个模式/对象的数组,包括 Joi 验证

问题描述

我正在尝试使用 node.js 为潜在的投资组合构建后端服务,以处理页面上发布的项目。我希望应用程序有一个单独的模型存储类别,我的项目模式包含一个类别数组。这是用于后端点。

const projectSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 50
  },
  collaborators: {
    type: [String],
    defualt: []
  },
  categories: {
    type: [categorySchema]
  },
  lastUpdated: {
    type: Date,
    default: Date.now
  }
});

这是我的项目架构。我认为的问题是当我尝试使用 Joi 验证输入时。因为如果我只使用一个类别而不是类别数组,应用程序就可以工作......

function validateProject(project) { const schema = {
    title: Joi.string()
      .min(2)
      .max(50)
      .required(),
    collaborators: Joi.array().items(Joi.string()),
    categoryIds: Joi.array().items(Joi.objectId())
    };

    return Joi.validate(project, schema);
}

是否无法以这种方式验证 objectId 数组?

我希望能够发布这样的项目:

{
    "title":"Test1",
    "collaborators": [
        "Name1",
        "Name2",
        "Name3"
    ],
    "categoryIds": [
        "5b7fa72a393c3c14f04066c6",
        "5b7fa76a7a714121b40f2266"
    ]
}

字符串数组有效,但由于某种原因,当我尝试使用 objectIds 数组时它只是挂起,而且我没有看到任何直接错误......

我的帖子端点如下所示:

router.post("/", [auth, admin], async (req, res) => {
  const { error } = validate(req.body);
  if (error) res.status(400).send(error.details[0].message);

  const categories = Category.find({
    _id: { $in: req.body.categoryIds }
  });
  if (!categories)
    res.status(400).send("Category with the given id was not found.");

  let project = new Project({
    title: req.body.title,
    collaborators: req.body.collaborators,
    categories
  });

  project = await project.save();

  res.send(project);
});

所有依赖项都是必需/导入的,所以这不应该是问题

标签: node.jsmongodbexpressmongoosejoi

解决方案


推荐阅读