Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Basic Validation with Mongoose | Section
Working with MongoDB in Express Applications

bookBasic Validation with Mongoose

Свайпніть щоб показати меню

When working with data, it is important to ensure that it has the correct structure.

Mongoose allows you to define simple validation rules in your schema.

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  age: {
    type: Number
  }
});

Here, the name field is required. If it is missing, Mongoose will not allow the document to be saved.

app.post('/users', async (req, res) => {
  try {
    const user = new User(req.body);
    const savedUser = await user.save();

    res.json(savedUser);
  } catch (error) {
    res.status(400).send('validation error');
  }
});

Validation helps prevent invalid or incomplete data from being stored in the database.

question mark

What does required: true do in a schema?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 13

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 1. Розділ 13
some-alt