Required Fields and Defaults
A required field must have a value before a document can be saved. A default fills in a value when none is given.
A required title
The title must have a value, or the save fails.
title: { type: String, required: true }A default value
The done flag starts as false when no value is given.
done: { type: Boolean, default: false }Both together
Priority starts at 1 unless a different value is given.
priority: { type: Number, default: 1 }Example
import mongoose from 'mongoose';
const noteSchema = new mongoose.Schema({
title: { type: String, required: true },
done: { type: Boolean, default: false },
priority: { type: Number, default: 1 }
});
const Note = mongoose.model('Note', noteSchema);
await mongoose.connect('mongodb://localhost:27017/notes');
await Note.create({ title: 'Buy milk' });
await Note.create({ title: 'Ship MERN', done: true, priority: 3 });
await Note.create({ title: 'Read a book' });
const notes = await Note.find();
console.log(notes.map(n => `${n.title}: ${n.done}`));
await mongoose.disconnect();Key points
- required: true marks a field as one that must have a value.
- Saving a document without a required field fails with an error.
- default sets the value used when a field is left out.
- A default runs when a document is created, not when it is read.
- A required field with a default is always filled, so it never fails.
In this example, the title is required and done defaults to false. Two notes leave done out, so the default fills it in. The printed list shows every note with its done value. The two notes without a given value both show false.
Note
Defaults apply only to new documents, never to documents already saved.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A note is saved without a done value. The schema sets done to default false. What is stored?