Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 37 Β· Schemas and Models

Mongoose Schema Types

Tour every common Mongoose schema type: String, Number, Date, Boolean, ObjectId, Buffer, Mixed, Map, Decimal128, arrays, plus per-type options and casting.

A schema type tells Mongoose how to cast, validate and store one field. Choosing the right type decides what values are accepted, how they are converted and which options are available. This lesson tours the types you will use daily, shows the options that belong to each, and explains casting so that you can predict what ends up in the database.

Declaring a type

There are three equivalent ways to say a field is a string:

JavaScript
const schema = new mongoose.Schema({
  a: String,                    // shorthand
  b: { type: String },          // object form
  c: { type: String, trim: true, minlength: 2 }, // object form with options
});

Use the object form as soon as you need any option. Nested plain objects group fields without creating a separate schema:

JavaScript
const schema = new mongoose.Schema({
  name: { first: String, last: String },   // nested path: name.first
});

The built-in types

Type Stores Notes
String Text Options: trim, lowercase, uppercase, enum, match, minlength, maxlength
Number 64-bit float (or integer) Options: min, max, enum
Date A date and time Options: min, max; stored as UTC
Boolean true or false Casts 'true', 'false', 1, 0
ObjectId A 12-byte identifier Use mongoose.Schema.Types.ObjectId; often with ref
Buffer Binary data For small binary values
Mixed Anything No casting or validation; see below
Map String keys to values Declared with of
Decimal128 Exact decimal Good for money; see below
UUID A UUID Stored as BSON binary
BigInt 64-bit integer Stored as a BSON long
Array List of values [String], [Number], [subSchema]

String options

String has the richest set of helpers. Setters such as trim and lowercase change the value on its way in:

JavaScript
const userSchema = new mongoose.Schema({
  email: { type: String, lowercase: true, trim: true, match: /^\S+@\S+\.\S+$/ },
  role: { type: String, enum: ['user', 'editor', 'admin'], default: 'user' },
  bio: { type: String, maxlength: 300 },
});

enum limits the allowed values, match takes a regular expression, and minlength/maxlength limit the length.

Number, Date and Boolean

JavaScript
const productSchema = new mongoose.Schema({
  price: { type: Number, min: 0, required: true },
  stock: { type: Number, min: 0, default: 0 },
  releasedAt: { type: Date, min: '2000-01-01' },
  inStock: { type: Boolean, default: true },
});

Number is a floating point value, so 0.1 + 0.2 is not exactly 0.3. For currency, either store integer cents (priceCents: Number) or use Decimal128. Dates are stored as UTC timestamps; formatting for a timezone is a job for your presentation layer.

ObjectId and references

JavaScript
const postSchema = new mongoose.Schema({
  title: String,
  author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
});

The ref option names the model whose _id this field points to, which later lets you replace the id with the real document using populate(). The population chapter explains it in depth; for now treat it as a typed pointer.

Mixed and Map

Mixed accepts anything and Mongoose cannot detect changes inside it, so you must call doc.markModified('path') after changing it. Prefer a defined structure whenever you can. A Map is the better choice for dynamic keys:

JavaScript
const settingsSchema = new mongoose.Schema({
  flags: { type: Map, of: Boolean },   // keys are strings, values are booleans
  extra: mongoose.Schema.Types.Mixed,   // anything at all
});

Maps keep keys as strings and values cast to the of type. Keys cannot contain . or start with $.

Arrays

An array of a type is written [Type]; Mongoose casts every element:

JavaScript
const articleSchema = new mongoose.Schema({
  tags: [String],
  scores: [Number],
  history: [{ at: Date, note: String }], // array of subdocuments
});

Arrays default to an empty array ([]), which surprises people who expect undefined. Set default: undefined on the array to avoid that. Subdocument arrays have their own lesson: Subdocuments and arrays.

Casting rules

Casting converts a value to the type you declared when it is assigned. If it cannot, the document fails validation with a CastError.

Value assigned To a Number To a String To a Boolean
'42' 42 '42' error
42 42 '42' error
'abc' error 'abc' error
'true' error 'true' true
null null null null

The stand-in below mimics two of these casts so you can try values yourself.

Node.js Casting values (simplified stand-in, not Mongoose)

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Exact decimals for money

A floating point number cannot represent every decimal fraction, which is a problem for prices. The classic demonstration works in any JavaScript runtime:

Node.js Why money needs care

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In Mongoose, Decimal128 values come back as Decimal128 objects; call .toString() to read them. Integer cents are usually simpler.

Type options every type supports

These options work on any schema type:

Option Purpose
required Value must be present
default Value or function used when the field is undefined
select Set false to hide the field from query results by default
index, unique Create an index (see the indexing chapter)
immutable Cannot change after the document is created
get, set Custom getter and setter, see Virtuals, getters and setters
validate Custom validator, see Custom validators

A type cheat sheet in pictures

Pick the right type

String Text, with enum and match
Number Counts, scores, cents
Date Moments in time, UTC
ObjectId Points to another document
1 / 2

Common mistakes with types

  • Writing type: 'String' with quotes. Pass the constructor (String), or the string alias 'String' only where documented.
  • Using a field named type in a nested object: { type: { type: String } } is required because type is reserved.
  • Storing prices as floating point numbers and being surprised by rounding.
  • Using Mixed and not calling markModified, so changes never save.
  • Forgetting that arrays default to [].

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Which schema type should you use for a field with dynamic string keys such as feature flags?

    Map stores string keys with values cast to the declared 'of' type, which is safer than Mixed.
  2. 2. What happens when you assign the string 'abc' to a Number field?

    Mongoose tries to cast, fails, and the document gets a CastError so the save is rejected.
  3. 3. How should you declare a field called type inside a nested schema object?

    The key type is reserved, so a field with that name needs the extra nesting.
  4. 4. What does the enum option on a String do?

    enum adds a validator that rejects values not in the list.

Summary

  • Declare a type with a constructor (String) or the object form { type: String, ...options }.
  • Common types: String, Number, Date, Boolean, ObjectId, Buffer, Mixed, Map, Decimal128, arrays.
  • Each type has its own options (enum, min, max, trim) plus shared options (required, default, select).
  • Mongoose casts values to the declared type and reports a CastError when it cannot.
  • For money use integer cents or Decimal128; for dynamic keys use Map instead of Mixed.

Next: Schema options and defaults