🎓 A1Learner
🔍
0 of 50 lessons completed

Schema Types

A schema type tells Mongoose what kind of value a field holds. Each field in a schema carries one type, and Mongoose checks values against it.

Text and true-or-false fields

String holds the title, and Boolean holds the done flag.

const noteSchema = new mongoose.Schema({
  title: String,
  done: Boolean
});

Numbers and dates

Number holds the priority, and Date holds the creation date.

const noteSchema = new mongoose.Schema({
  priority: Number,
  createdAt: Date
});

A list field

An array type holds a list of values of one type.

const noteSchema = new mongoose.Schema({
  tags: [String]
});

Example

import mongoose from 'mongoose';

const noteSchema = new mongoose.Schema({
  title: String,
  done: Boolean,
  priority: Number,
  createdAt: Date
});

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

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

await Note.create({ title: 'Buy milk', done: false, priority: 1, createdAt: new Date('2026-11-09T00:00:00.000Z') });
await Note.create({ title: 'Ship MERN', done: true, priority: 3, createdAt: new Date('2026-11-09T00:00:00.000Z') });
await Note.create({ title: 'Read a book', done: false, priority: 2, createdAt: new Date('2026-11-09T00:00:00.000Z') });

const notes = await Note.find();
console.log(notes.map(n => `${n.title}: ${n.priority}`));

await mongoose.disconnect();

Key points

  • String holds text, such as a note title.
  • Number holds a numeric value, such as a priority.
  • Boolean holds true or false, such as a done flag.
  • Date holds a calendar date and time.
  • An array type holds a list of values of one type.
  • Mongoose casts a value to the field type when it can.

In this example, the schema gives each field a type. String holds the title, Boolean holds the done flag, Number holds the priority, and Date holds the creation date. Three notes are saved, then read back in title order. The printed list shows each title with its priority, so the Number type is visible in the output.

Note

The type is chosen in the schema, before any document is saved.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which schema type holds a true or false value?