简体   繁体   English

如何使用文件中的验证模式验证 MongoDB 文档?

[英]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.

相关问题 如何验证 mongodb 模式中的列表? - How to validate list in mongodb schema? 如何在 node.js 上使用 mongoose 从 mongodb 库检索文档? - How can I retrieve document from mongodb base using mongoose on node.js? 如何从 mongoose 架构中拼接项目然后保存文档或架构? - How can i splice an item from a mongoose schema then save the document or schema? 如何从 mongoDb 文档中访问第二个 _id? - how can I access the second _id from the mongoDb document? 我如何在 mongoDB 中将 2 个模式与 _id 连接起来 - How can i connect 2 schema with _id in mongoDB 如何在作为教师模式一部分的 MongoDB 中为时间表创建模式? - How can I create a schema for timetables in MongoDB that is part of a Teacher Schema? 如何在 onBlur 上同时使用同步和异步验证规则来验证表单字段? - How can I can validate form fields using sync and async validation rules together on onBlur? 如何从MongoDb集合中获取随机文档,然后在HTML中显示随机选择的文档的每个字段? - How can I get a random document from a MongoDb collection, and then display each of the fields of that randomly selected document in HTML? 如何使用正则表达式验证我的文件输入名称? - How can I validate my file input name using regex? 如何验证 mongoose 架构中字符串数组的最大长度? - How can I validate maxlength of a array of strings in mongoose schema?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM