intermediate

Models

Represent collection operations through compiled models and understand how queries, documents, and lean results differ.

A Mongoose model is a compiled schema bound to a collection. It creates documents, runs queries, applies middleware, and returns hydrated documents unless `.lean()` is used.

| Result type | Behavior | |-------------|----------| | Hydrated document | Methods, change tracking, middleware | | Lean plain object | Faster reads, no Mongoose methods |

					const Order = model('Order', orderSchema);
const doc = await Order.findById(id);      // hydrated
const row = await Order.findById(id).lean(); // plain object
				

On interviews: mention compilation per connection, query execution timing, hydration cost, and document versus static methods.

Common pitfalls: hydrated documents in read-heavy APIs; recompiling models on hot reload without guarding registration; assuming queries run when the query object is built.

The trade-off is convenience and middleware hooks versus memory and serialization cost.

Checklist:

  • Know when queries actually execute.
  • Use lean for read-heavy plain objects.
  • Manage model registration per connection.
  • Separate persistence documents from API DTOs.