← Back to Node.js, page 9

nodejs-0172 · Easy fresher

How do Mongoose schemas handle types, validation, defaults, virtuals and hooks, and what happens when you query without a connection?

Mongoose adds a schema layer to MongoDB: typed fields, casting, defaults, validators, virtual fields, middleware hooks and a model class. Validation runs on save (and with validate()) in Node before data reaches the database. Unknown fields are dropped in strict mode. Queries are buffered until a connection exists, so a missing connection looks like a hang until bufferTimeoutMS triggers an error.

Full answer

Why Mongoose

  • MongoDB stores flexible documents. An application still needs rules: required fields, allowed ranges, defaults and the same shape for every writer. Mongoose provides those rules in Node (an ODM, object document mapper).

Schema features

  • Types and casting: a String of '78' sent to a Number field is cast to 78. A value that cannot be cast (abc) fails with a CastError.
  • Validation: required, min, max, enum, match, minLength, custom validate functions. doc.validate() rejects with a ValidationError with details per path. Validation also runs automatically on save().
  • Defaults: default: Date.now or a value.
  • strict mode (default): fields not in the schema are not saved.
  • Virtuals: computed properties (fullName) that are not stored. Include them in JSON with toJSON({ virtuals: true }).
  • Middleware (hooks): pre and post for validate, save, find and others. Typical use: hashing a password, updating timestamps. In pre hooks call next() or return a promise.
  • Options: timestamps: true adds createdAt and updatedAt. Indexes are declared in the schema (autoIndex is usually off in production, build indexes in migrations).

Operational notes

  • Connection: await mongoose.connect(uri). Commands issued before the connection is ready are buffered. If the connection never opens, they wait (default 10 seconds) and then fail with a buffering timeout error. Handle connection errors and events.
  • lean() returns plain objects, which is faster and uses less memory for read-only queries.
  • Mongoose validation does not replace database-level rules (unique indexes are created in MongoDB, not checked by Mongoose validators).
  • Use populate carefully, because it runs extra queries (a form of N+1).
javascript
const mongoose = require('mongoose');
mongoose.set('bufferTimeoutMS', 100);          // fail fast in this demo

const studentSchema = new mongoose.Schema({
  name: { type: String, required: [true, 'name is required'], trim: true },
  marks: { type: Number, min: [0, 'marks cannot be negative'], max: [100, 'marks cannot be above 100'], default: 0 },
  track: { type: String, enum: ['web', 'data'], default: 'web' },
  firstName: String,
  lastName: String,
}, { timestamps: false });
studentSchema.virtual('fullName').get(function () { return `${this.firstName} ${this.lastName}`; });
studentSchema.pre('validate', function () { this.name = this.name && this.name.replace(/\s+/g, ' '); });   // a hook that tidies input
const Student = mongoose.model('Student', studentSchema);

(async () => {
  const ok = new Student({ name: '  Asha   Rao ', marks: '78', firstName: 'Asha', lastName: 'Rao', hobby: 'chess' });
  await ok.validate();
  console.log('cast and trim :', JSON.stringify({ name: ok.name, marks: ok.marks, type: typeof ok.marks, track: ok.track }));
  console.log('unknown field :', ok.get('hobby') === undefined ? 'dropped (strict mode)' : 'kept');
  console.log('virtual       :', JSON.stringify(ok.toJSON({ virtuals: true }).fullName));

  const bad = new Student({ marks: 150, track: 'art' });
  const error = await bad.validate().catch((e) => e);
  console.log('validation    :', error.name, '->', Object.entries(error.errors).sort(([a], [b]) => a.localeCompare(b)).map(([path, e]) => `${path}: ${e.message}`).join(' | '));

  const notANumber = new Student({ name: 'Ravi', marks: 'abc' });
  console.log('cast error    :', (await notANumber.validate().catch((e) => e)).errors.marks.name);

  // No connection was opened, so the query waits and then fails.
  await Student.findOne({ name: 'Asha' }).catch((err) => console.log('no connection :', err.name + ':', err.message));
})();

Everything here runs without a MongoDB server. The query at the end shows what happens when no connection exists, and queries that need a real server were not run. Install first with npm install mongoose (run here with mongoose 9.13.2). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): cast and trim : {"name":"Asha Rao","marks":78,"type":"number","track":"web"} unknown field : dropped (strict mode) virtual : "Asha Rao" validation : ValidationError -> marks: marks cannot be above 100 | name: name is required | track: `art` is not a valid enum value for path `track`. cast error : CastError no connection : MongooseError: Operation `students.findOne()` buffering timed out after 100ms

Key points

  • A Mongoose schema defines types, casting, defaults and validators.
  • Validation runs in Node before data is sent.
  • Strict mode drops unknown fields.
  • Virtuals are computed fields; hooks run around save and validate.
  • Without a connection, queries are buffered and then time out.

Common mistakes

  • Assuming Mongoose validators create unique indexes.
  • Not handling connection errors and seeing queries hang.
  • Using populate in loops without thinking about the extra queries.
  • Letting the schema grow with no versioning of old documents.
  • Auto-building indexes in production on startup.

Follow-ups

  • What does lean() change?
  • How do you add an index and a unique constraint?
  • How do pre and post hooks differ?

Tips

  • Say 'schema layer on top of flexible documents'.
  • Name casting, validation, virtuals, hooks.
  • Mention buffering.