我目前正在努力在nodeJS,mongoDB,express中实现rest api构建。字段之一采用对象ID的数组(模型项目中的字段sprint)。问题是在执行post方法时如何在路由文件(projects.js)中进行适当的验证(请记住,不需要字段sprint)?
我试图检查 req.body.sprints的类型,并对此进行 lenght ,但没有结果。我也在尝试寻找关于stackoverflow等的答案,但没有遇到类似的问题。
project.js(模型文件)
const mongoose = require("mongoose");
const Project = mongoose.model(
"Project",
new mongoose.Schema({
name: {
...
sprints: [
{
type: new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 255
},
isClosed: { type: Boolean, default: false }
})
}
]
})
);
function validateProject(project) {
const schema = {
name: Joi.string()
.min(5)
.max(255)
.required(),
createdBy: Joi.objectId().required(),
isClosed: Joi.boolean(),
sprints: Joi.array().items(Joi.objectId())
};
return Joi.validate(project, schema);
}
exports.Project = Project;
exports.validate = validateProject;
projects.js(路由文件)
const express = require("express");
const { User } = require("../models/user");
const { Sprint } = require("../models/sprint");
const { Project, validate } = require("../models/project");
const router = express.Router();
...
/* POST project */
router.post("/", async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
const user = await User.findById(req.body.createdBy);
if (!user) return res.status(400).send("Invalid user");
const sprint = await Sprint.findById(req.body.sprints);
if (!sprint) return res.status(400).send("Invalid sprint");
//i think that here i have to validate if sprint has even one
element and only then do object id validation
const project = new Project({
name: req.body.name,
createDate: req.body.createDate,
createdBy: { _id: user._id, name: user.name },
isClosed: req.body.isClosed,
sprints: [
{
_id: sprint._id,
name: sprint.name,
isClosed: sprint.isClosed
}
]
});
await project.save();
res.send(project);
});
...
module.exports = router;
在我的post方法中,我正在检查表Sprint中是否存在给定的ID,但是如果没有提供Sprint ID,我会遇到问题(我收到“ Invalid sprint”消息)。预期结果将是:我可以提供一组sprint,一个sprint或根本不提供。
答案 0 :(得分:1)
尝试一下
function validateProject(project) {
const schema = {
name: Joi.string()
.min(5)
.max(255)
.required(),
createdBy: Joi.objectId().required(),
isClosed: Joi.boolean(),
sprints:Joi.array().items(
Joi.object({
name: Joi.string(),
isClosed: Joi.boolean
})
)
})
};
return Joi.validate(project, schema);
}