简体   繁体   中英

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.

//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) .

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 install joi

Import Joi and Define Validation Schema:-

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.

Perform Validation: Now you can use the validate() method provided by Joi for the validation.

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:

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.');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM