Mongoose模式可选,带有验证功能



给定这样的模式:

new Schema(
{
someData: {
someString: {
required: false,
maxlength: 400,
type: String
}
otherData: {
required: true,
type: String
}
});

someString是可选的,但有一个验证来检查它的长度是否低于400。

如果给我一个无效长度的字符串(>400(,这个对象是否仍然会被保存,但没有someString,或者这会引发错误?如果这引发了一个错误,我该如何更改模式以使对象仍然可以保存?

它将在不保存文档的情况下抛出错误。

假设我们有这样的模式:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const studentSchema = new Schema({
someData: {
someString: {
required: false,
maxlength: 5,
type: String
},
otherData: {
required: true,
type: String
}
}
});
module.exports = mongoose.model("Student", studentSchema);

这条邮寄路线:

const Student = require("../models/student");
router.post("/students", async (req, res) => {
try {
const result = await Student.create(req.body);
res.send(result);
} catch (err) {
console.log(err);
if (err.name === "ValidationError") {
return res.status(400).send(err.errors);
}
res.status(500).send("Something went wrong");
}
});

当我们发送错误请求时,它会给出ValidationError,我们可以从err.errors中读取错误详细信息。

请求主体:

{
"someData": {
"someString": "123456",
"otherData": "other"
}
}

响应将是:

{
"someData.someString": {
"message": "Path `someData.someString` (`123456`) is longer than the maximum allowed length (5).",
"name": "ValidatorError",
"properties": {
"message": "Path `someData.someString` (`123456`) is longer than the maximum allowed length (5).",
"type": "maxlength",
"maxlength": 5,
"path": "someData.someString",
"value": "123456"
},
"kind": "maxlength",
"path": "someData.someString",
"value": "123456"
}
}

您可以通过删除maxlength选项来解决此问题,或者检查路由中字段的长度,如果字段的长度大于指定的最大长度,则可以对其进行减法运算,这样就不会导致错误。

router.post("/students", async (req, res) => {
try {
let doc = req.body;
if (doc.someData && doc.someData.someString && doc.someData.someString.length > 5) {
doc.someData.someString = doc.someData.someString.substring(0, 5);
}
const result = await Student.create(doc);
res.send(result);
} catch (err) {
console.log(err);
if (err.name === "ValidationError") {
return res.status(400).send(err.errors);
}
res.status(500).send("Something went wrong");
}
});

相关内容

  • 没有找到相关文章

最新更新