Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Basic Validation with Mongoose | Section
Working with MongoDB in Express Applications

bookBasic Validation with Mongoose

Swipe um das Menü anzuzeigen

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?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 13

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 13
some-alt