node.js - 从 _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);
});
所有依赖项都是必需/导入的,所以这不应该是问题
解决方案
推荐阅读
- visual-studio-code - 如何在自定义片段中自动大写用户输入
- python-3.x - 1. 从字符串中删除所有小写字母。输入="amiT123" 输出="T123"
- c# - SQL Server db 在不运行更新数据库的情况下更新项目构建(使用 EF6 和代码优先迁移)
- python-3.x - 使用 cv2 进行灰度图像旋转
- php - 如何将本地文件夹的多个文件上传到ftp文件夹?
- excel - 自动格式化提前结束
- c - 如何将 Python 字符串列表转换为 wchar_t 的 C 数组?
- python - 无法在评论删除页面显示帖子标题
- docker - Docker 中的 Kubernetes 集群是什么?
- r - 在 dplyr 管道中加入非 R 标准列名