[英]How can I validate a MongoDB document using a validation schema from a file?
I want to validate document before it is inserted into the database.我想在将文档插入数据库之前对其进行验证。 I know that I can set static validator, but I would prefer to have a file with the validation schemas that I could modify at any time.我知道我可以设置 static 验证器,但我更希望有一个包含我可以随时修改的验证模式的文件。
//example schema
const userCreateValidationSchema = {
bsonType: 'object',
required: ['username', 'password'],
properties: {
username: {
bsonType: 'string',
maxLength: 16,
},
password: {
bsonType: 'string',
maxLength: 64,
},
},
additionalProperties: false,
};
//example document
const document = {
username: "user",
password: "passwd",
};
Then I would do something like validate(document, userCreateValidationSchema)
.然后我会做类似validate(document, userCreateValidationSchema)
事情。
Thanks for any thoughts.感谢您的任何想法。
I have tried looking for the answer in the documentation but unfortunatelly didn't find the solution.我曾尝试在文档中寻找答案,但不幸的是没有找到解决方案。
To perform login validation using the npm package Joi:-要使用 npm package Joi 执行登录验证:-
npm install joi
Import Joi and Define Validation Schema:-导入 Joi 并定义验证模式:-
const Joi = require('joi');
const loginSchema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().min(6).required(),
});
In the above example, the validation schema requires the email field to be a valid email address and the password field to have a minimum length of 6 characters.在上面的示例中,验证模式要求 email 字段是有效的 email 地址,密码字段的最小长度为 6 个字符。
Perform Validation: Now you can use the validate()
method provided by Joi for the validation.执行验证:现在您可以使用 Joi 提供的validate()
方法进行验证。
function validateLogin(loginData) {
const { error, value } = loginSchema.validate(loginData);
return error ? error.details[0].message : null;
}
Usage Example: Here's an example of how you can use the validateLogin() function to validate the login data:使用示例:这是一个如何使用 validateLogin() function 验证登录数据的示例:
const loginData = {
email: 'test@example.com',
password: 'password123',
};
const validationError = validateLogin(loginData);
if (validationError) {
console.log('Login validation failed:', validationError);
} else {
console.log('Login data is valid.');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.