Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 37 ยท Schemas and Models

Mongoose Schema Options, Defaults and Timestamps

Configure Mongoose schemas with options: timestamps, strict, collection, versionKey, toJSON, minimize and default values including dynamic defaults.

A schema has two parts: the definition (the fields) and the options (how the schema behaves). Options are passed as the second argument to new mongoose.Schema(definition, options). This lesson covers the options you will use most often, then goes deeper on default values, which have several subtle behaviors.

JavaScript
const schema = new mongoose.Schema(
  { name: String },
  { timestamps: true, collection: 'people' }
);

timestamps

timestamps: true adds two Date fields, createdAt and updatedAt. Mongoose sets createdAt once when the document is first saved and refreshes updatedAt on every save and on update operations such as updateOne and findOneAndUpdate.

JavaScript
const postSchema = new mongoose.Schema({ title: String }, { timestamps: true });

You can rename the fields:

JavaScript
{ timestamps: { createdAt: 'created', updatedAt: 'modified' } }
{ timestamps: { createdAt: 'created', updatedAt: false } } // only creation time

This option replaces the hand-written default: Date.now pattern for most cases and has the advantage of tracking updates as well.

Node.js How timestamps behave (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.

strict

By default Mongoose is in strict mode: fields not in the schema are not saved. Other values:

Value Behavior
true (default) Unknown fields are ignored
false Unknown fields are saved too
'throw' Assigning an unknown field throws an error
JavaScript
new mongoose.Schema({ name: String }, { strict: 'throw' });

Use 'throw' in development to catch typos early. Leave strict on in production; turning it off lets a user-supplied request body write any field into your database, a mass assignment risk.

There is a sibling option, strictQuery, which controls whether unknown fields in a query filter are ignored. Mongoose 7 and later default it to false, meaning filters are passed through as written; set mongoose.set('strictQuery', true) to drop unknown fields from filters.

collection

Override the default pluralized collection name:

JavaScript
new mongoose.Schema({ name: String }, { collection: 'people' });
// or: mongoose.model('Person', schema, 'people')

This is also how you attach a model to a collection created by another system, with a name that Mongoose would not guess.

versionKey

Mongoose adds __v to every document. It is used to detect conflicting array updates on save(). You can rename it or disable it:

JavaScript
{ versionKey: 'revision' }
{ versionKey: false }

Disabling is common for collections that never use arrays with save(), but it removes a safety net, so do it deliberately.

toJSON and toObject

These options control how a document turns into plain data, which matters for API responses:

JavaScript
const userSchema = new mongoose.Schema(
  { name: String, passwordHash: String },
  {
    toJSON: {
      virtuals: true,
      versionKey: false,
      transform(doc, ret) {
        delete ret.passwordHash;
        ret.id = ret._id;
        delete ret._id;
        return ret;
      },
    },
  }
);

The transform function runs on every toJSON() call, so JSON.stringify(user) never leaks the hash. The stand-in below shows the effect of a transform without needing Mongoose.

Node.js A toJSON transform (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.

minimize

Mongoose removes empty objects before saving to keep documents small: { address: {} } is stored without address. Set minimize: false if you need the empty object to be stored.

Other options worth knowing

Option What it does
_id: false Do not add _id; common for embedded sub-schemas
id: false Remove the id virtual (a string copy of _id)
autoIndex Build declared indexes automatically at startup
autoCreate Create the collection automatically
discriminatorKey Name of the field that records which sub-model a document uses
read Default read preference
optimisticConcurrency Fail saves when the version has changed
validateBeforeSave Set false to skip validation on save
selectPopulatedPaths Control field selection of populated paths

Global defaults can be set for all schemas with mongoose.set('strictQuery', true) and similar calls.

Defaults in depth

A default is used when the field is undefined. It can be a value or a function:

JavaScript
const taskSchema = new mongoose.Schema({
  status: { type: String, default: 'todo' },
  createdAt: { type: Date, default: Date.now },
  code: { type: String, default: () => Math.random().toString(36).slice(2, 8) },
});

Rules to remember:

  1. Functions run per document. Date.now and arrow functions are invoked for each new document. A plain value is shared in the schema definition, which is fine for primitives.
  2. Arrays and objects need a function if you want a fresh one each time: default: () => ({}). (Mongoose copies array defaults, but the function form is clear and safe.)
  3. Defaults apply to missing values only. Setting a field to null explicitly keeps the null.
  4. Defaults run when the document is constructed, and also when you query with a projection that includes the field (a field missing in the database appears with its default in the document, though the database is not changed).
  5. Defaults do not run on updates such as updateOne, unless you pass setDefaultsOnInsert for upserts. Do not rely on them to patch old documents.
  6. A default function receives the document as this, so with a normal function (not an arrow function) it can depend on other fields.
Node.js Dynamic defaults (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.

Common mistakes

  • default: Date.now() instead of default: Date.now.
  • Turning off strict to "make something work" and then storing arbitrary client data.
  • Expecting timestamps to update when you use Model.updateMany with { timestamps: false } or a low-level driver call.
  • Expecting defaults to fix old documents in the database.
  • Returning _id and __v to API clients when a toJSON transform would tidy them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the timestamps: true option add?

    createdAt is set once and updatedAt is refreshed on saves and updates.
  2. 2. What happens in strict: 'throw' mode when you assign a field that is not in the schema?

    'throw' turns unknown fields from a silent drop into an error, which is helpful during development.
  3. 3. Which default is correct for a field that should hold a fresh empty object per document?

    A function is called for each document, so each one gets its own object.
  4. 4. When is a schema default applied?

    Defaults fill undefined values. An explicit null stays null.

Summary

  • Options go in the second argument of new Schema(definition, options).
  • timestamps adds createdAt/updatedAt; strict controls unknown fields; collection names the collection.
  • toJSON with a transform shapes API output and hides sensitive fields.
  • Defaults can be values or functions; they apply to undefined values at construction, not to updates.

Next: Virtuals, getters and setters