🎓 A1Learner
🔍
0 of 50 lessons completed

Validation

Validation checks a document against the schema rules before it is saved. A document that breaks a rule is refused, and Mongoose reports the problem.

Shortest text

The title needs at least three letters.

title: { type: String, minlength: 3 }

Number range

The priority must sit between 1 and 5.

priority: { type: Number, min: 1, max: 5 }

Allowed words

The status must be one of the two listed words.

status: { type: String, enum: ['open', 'done'] }

Example

import mongoose from 'mongoose';

const noteSchema = new mongoose.Schema({
  title: { type: String, required: true, minlength: 3 },
  done: { type: Boolean, default: false },
  priority: { type: Number, min: 1, max: 5 }
});

const Note = mongoose.model('Note', noteSchema);

await mongoose.connect('mongodb://localhost:27017/notes');

try {
  await Note.create({ title: 'Hi', priority: 1 });
} catch (err) {
  console.log(err.message);
}

await Note.create({ title: 'Buy milk', done: false, priority: 1 });
await Note.create({ title: 'Ship MERN', done: true, priority: 3 });
await Note.create({ title: 'Read a book', done: false, priority: 2 });

const notes = await Note.find();
console.log(notes.map(n => n.title));

await mongoose.disconnect();

Key points

  • Validation runs automatically each time a document is saved.
  • minlength sets the shortest text a String field may hold.
  • min and max set the smallest and largest values a Number field may hold.
  • enum limits a String field to a fixed list of allowed words.
  • A failed check stops the save and raises a validation error.

In this example, the title needs at least three letters. A note titled 'Hi' breaks that rule, so the save fails and the error message is printed. Three valid notes are then saved, and the printed list shows their titles in order.

Note

Validation checks the values, not the shape of the database.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which rule limits a String field to a fixed list of allowed words?