Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Validation in Schemas | Advanced Mongoose Features
MongoDB and Mongoose Essentials

Validation in Schemas

Pyyhkäise näyttääksesi valikon

When designing a schema in Mongoose, you can define validation rules to ensure your data meets certain requirements before it is saved to the database. Here is an example of a User schema that demonstrates several validation features:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true, // This field must be present
    minlength: 3,   // Must be at least 3 characters long
    // Custom validator to ensure username does not contain spaces
    validate: {
      validator: function(value) {
        return !/\s/.test(value); // Returns true if no spaces are found
      },
      message: 'Username must not contain spaces.'
    }
  },
  email: {
    type: String,
    required: [true, 'Email is required'], // Custom error message
    // Custom validator for email format
    validate: {
      validator: function(value) {
        // Simple regex for demonstration purposes
        return /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/.test(value);
      },
      message: 'Email must be a valid email address.'
    }
  },
  password: {
    type: String,
    required: true,
    minlength: [6, 'Password must be at least 6 characters long']
  }
});

Mongoose applies validation rules automatically when you attempt to save a document. In the schema above, the username field is required, must be at least three characters, and must not contain spaces. The email field is required and must match a simple email pattern. The password field is required and must be at least six characters long.

If any of these validation rules fail, Mongoose will not save the document and will instead throw a ValidationError. You can handle these errors in your application code by catching them and responding appropriately. For example, when you try to create a new User:

const User = mongoose.model('User', userSchema);

const newUser = new User({
  username: 'ab', // Too short, will fail minlength
  email: 'notanemail', // Invalid email format
  password: 'pass' // Too short
});

newUser.save()
  .then(() => {
    console.log('User saved successfully');
  })
  .catch(err => {
    if (err.name === 'ValidationError') {
      // Handle validation errors
      for (field in err.errors) {
        console.log(err.errors[field].message);
      }
    } else {
      // Handle other errors
      console.log('An error occurred:', err);
    }
  });

When validation fails, the error object contains details about which fields failed and why, allowing you to provide clear feedback to users or trigger other logic in your application. By using built-in validators like required and minlength, along with custom validator functions, you can enforce a wide range of data integrity rules directly in your Mongoose schemas.

question mark

Which of the following statements about Mongoose validation are correct?

Valitse kaikki oikeat vastaukset

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 4. Luku 1

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 4. Luku 1
some-alt