Coding Hub  /  Reference  /  Node unit

mongodb & mongoose

The database, and the library that puts rules in front of it. Filter the page to jump straight to an operator, a validator or an error.

Part one: the database

MongoDB stores documents, not rows. Most of what feels strange about it comes from that one difference.

01 The vocabulary

If you have seen a spreadsheet or a SQL table, the mapping is close enough to get started with.

The real difference is the last row. A SQL table fixes its columns in advance for every row. A MongoDB collection does not: two documents side by side can hold different fields. That freedom is why Mongoose exists — it puts the structure back, in your code, where you can see it.

if you know tables
SQLMongoDBIn your code
databasedatabasethe end of your connection string
tablecollectioncreated from a model, named as a lowercase plural
rowdocumentone object
columnfieldone key on that object
primary key_idgenerated for you
schema, fixed by the databaseno schema at allthe schema lives in Mongoose instead

02 Documents and _id

A document is close to a JSON object, with a few extra types — dates, and the ObjectId that every document gets as its _id.

An ObjectId is 24 hexadecimal characters, generated when the document is created. The first part of it is a timestamp, which is why sorting by _id is almost the same as sorting by creation time.

It is an object, not a string. id === user._id is false even when they look identical; compare with String(user._id) or user._id.equals(id).

one document
{
  "_id": "6ad140c552a2615ba5f2ef3f",
  "title": "The Hobbit",
  "author": "J.R.R. Tolkien",
  "year": 1937,
  "tags": ["fantasy", "classic"],
  "inStock": true,
  "createdAt": "2026-10-20T19:14:51.502Z"
}

03 Connecting

Connect once, when the server starts, and keep the connection. Do not connect inside a route handler.

Mongoose reconnects by itself after a network blip, which is convenient and also means a dropped connection is silent unless you listen for it. Attach the listeners so your terminal tells you.

If a query hangs for ten seconds and then throws about buffering, you are not connected. Mongoose queues queries while it waits for a connection that never arrives.

src/config/database.js
const mongoose = require('mongoose')

async function connectDatabase(uri){
  // Strip query fields that are not in the schema instead of
  // forwarding them to MongoDB
  mongoose.set('strictQuery', true)

  mongoose.connection.on('connected',    () => console.log('MongoDB connected'))
  mongoose.connection.on('error',   (e) => console.log('MongoDB error:', e.message))
  mongoose.connection.on('disconnected', () => console.log('MongoDB disconnected'))

  await mongoose.connect(uri, {
    // Fail fast rather than hanging for the 30s default
    serverSelectionTimeoutMS: 10000
  })
}
connection states
readyStateMeans
0disconnected
1connected — the one to check for in a health route
2connecting
3disconnecting

Part two: schemas and models

The schema is where your rules live. Everything you put here, you never have to check again in a controller.

04 Schema, model, document

Three words that get mixed up constantly, so here they are side by side.

A schema is the description: fields, types, rules. A model is the thing you call methods on, built from a schema and bound to a collection. A document is one record that came out of a model.

Model names are singular and capitalised: Book, not books. Mongoose lowercases and pluralises the name to find the collection, so Book reads and writes books.

the three
// 1. Schema — the description
const bookSchema = new mongoose.Schema({ title: String })

// 2. Model — what you call methods on
const Book = mongoose.model('Book', bookSchema)   // -> "books" collection

// 3. Document — one record
const book = await Book.findById(id)
book.title               // a field
book.save()              // documents have methods, models have their own

05 Field types

The types you will actually use. A field can be written as a bare type when it has no other rules, or as an object once it does.

types
TypeWritten asNotes
StringStringTakes trim, lowercase, uppercase
NumberNumbermin and max apply
BooleanBoolean
DateDateAccepts a Date or an ISO string
Array[String]Defaults to [], not undefined
ObjectIdmongoose.Schema.Types.ObjectIdUse with ref to point at another model
Mixedmongoose.Schema.Types.MixedNo validation at all. Avoid.
short form and long form
const bookSchema = new mongoose.Schema({
  title: String,                      // short form, no rules

  author: {                           // long form, once rules appear
    type: String,
    required: [true, 'author required'],
    trim: true,
    maxlength: [80, 'author cannot exceed 80 characters']
  },

  tags: [String],                     // array of strings
  year: { type: Number, min: 1450 },
  inStock: { type: Boolean, default: true }
})

06 Validators

Pass an array of [rule, message] and you control what the client is told. Pass the bare rule and you get Mongoose's own wording, which is rarely what you want in an API response.

unique is not a validator. It builds a database index, so a duplicate fails as a driver error with code 11000, not a ValidationError. Your error handler has to catch it separately and turn it into a 409.

In an enum message, {VALUE} is replaced with what the client sent. Drop the closing brace and the message prints the literal text instead — an easy typo to stare past.

validators
ValidatorApplies toExample
requiredany[true, 'title required']
minlength / maxlengthString[60, 'too long']
min / maxNumber, Date[1, 'must be at least 1']
enumString{ values: [...], message: '{VALUE} is not allowed' }
matchString[/^\S+@\S+$/, 'invalid email']
validateanyYour own function returning true or false
uniqueanyindex not a validator — see above

07 Schema options

The second argument to new mongoose.Schema(). Two of them earn their place in every model you write.

timestamps adds and maintains createdAt and updatedAt with no further work. The toJSON transform decides what the outside world sees, which is where you rename _id to id and delete anything private.

the options block
const bookSchema = new mongoose.Schema({ /* fields */ }, {
  timestamps: true,            // adds createdAt and updatedAt

  toJSON: {
    virtuals: true,            // include computed fields
    versionKey: false,         // drop __v
    transform(doc, ret){
      ret.id = ret._id         // friendlier key name
      delete ret._id
      return ret
    }
  },

  toObject: { virtuals: true }
})

08 Virtuals

A virtual is a field computed when you read it and never stored. Use one whenever a value can be derived from fields you already have, instead of saving a copy that can drift out of date.

Because a virtual is not in the database, you cannot query or sort on it. find({ isOverdue: true }) silently matches nothing. Filtering on a derived value needs either a real stored field or an aggregation.

a virtual
bookSchema.virtual('age').get(function (){
  return new Date().getFullYear() - this.year
})

// Reading it
book.age        // 89

// It only appears in JSON when virtuals:true is set in toJSON

09 Methods, statics, hooks

Three places to hang behaviour, distinguished by what they belong to.

A method runs on one document. A static runs on the model. A hook runs around an operation, which is where password hashing goes.

All three need function, not an arrow function. An arrow has no this of its own, so this.title is undefined and the whole thing quietly does nothing.

all three
// Method — on one document
bookSchema.methods.markBorrowed = function (){
  this.inStock = false
  return this
}
book.markBorrowed()

// Static — on the model
bookSchema.statics.findByAuthor = function (author){
  return this.find({ author })
}
await Book.findByAuthor('Tolkien')

// Hook — around an operation
bookSchema.pre('save', function (){
  if(this.isModified('title')) this.slug = slugify(this.title)
})

10 Indexes

An index is a sorted lookup kept beside the collection. Without one, finding a document means reading every document; with one, the database jumps straight there.

Index the fields you filter and sort on. Do not index everything — every index costs time on each write and space on disk.

In a compound index the field order matters. {status: 1, location: 1} helps a query on status alone, and a query on both, but not one on location alone.

declaring indexes
// On the field
email: { type: String, unique: true }
ownerId: { type: ObjectId, ref: 'User', index: true }

// On the schema. 1 is ascending, -1 descending.
bookSchema.index({ status: 1, location: 1 })
bookSchema.index({ createdAt: -1 })

// Check what actually got built, in mongosh:
//   db.books.getIndexes()

Part three: queries

Everything that reads or writes. The operator playground below is the fastest way to get these into your head.

11 Create, read, update, delete

The methods you will use daily. All of them return promises, so all of them want await.

A find that matches nothing returns [], but findById and findOne return null. Check for null before you read a property off the result, or you get Cannot read properties of null and a 500 where you wanted a 404.

the methods
CallReturnsNot found
Model.create(obj)the new document—
Model.insertMany([...])array of documents—
Model.find(filter)array[]
Model.findOne(filter)one documentnull
Model.findById(id)one documentnull
Model.countDocuments(filter)number0
Model.findByIdAndUpdate(id, patch, opts)documentnull
Model.updateMany(filter, patch)a result summarymatchedCount: 0
Model.findByIdAndDelete(id)the deleted documentnull
Model.deleteMany(filter)a result summarydeletedCount: 0
doc.save()the document—

12 Filter operators

A filter is an object. A bare value means equals; anything cleverer uses an operator starting with $.

Edit the filter and watch which books match. The matching below is a simplified version of what MongoDB does, built to make the operators visible — the real database does more, but these rules are the ones you will use.

operator playground

  
operators
OperatorMatches when
{ field: value }equal — or, for an array field, the array contains the value
$eq / $neequal / not equal
$gt $gte $lt $ltegreater / less, with e for "or equal"
$in / $ninthe value is / is not in the given list
$existsthe field is present (true) or absent (false)
$regexthe string matches; add $options: "i" to ignore case
$or / $andany / all of an array of filters match
$allan array field holds every listed value
$sizean array field has exactly that many entries
the sample collection

  

13 Shaping results

Chain these onto a query to decide how much comes back and in what order. Nothing runs until the query is awaited.

This is how pagination is built: skip steps over the pages before the one you want, limit takes one page. Always pair them with a sort, because without one the order is not guaranteed and the same record can appear on two pages.

chainable
CallDoes
.sort({ createdAt: -1 })Order results. -1 descending, 1 ascending. Also takes '-createdAt'.
.skip(n)Step over the first n matches
.limit(n)Return at most n
.select('title year')Only these fields. '-password' excludes instead.
.select('+password')Include a field the schema hid with select: false
.lean()Plain objects instead of documents. Faster, but no virtuals, no methods, no save.
.populate('ownerId')Swap a reference for the document it points at
a paginated list
const page = 2, limit = 20
const filter = { genre: 'fantasy' }

// Both queries run together, and both use the same filter so the
// count describes the filtered set rather than the whole collection
const [books, total] = await Promise.all([
  Book.find(filter).sort({ createdAt: -1 }).skip((page - 1) * limit).limit(limit),
  Book.countDocuments(filter)
])

14 Updating safely

Two options on findByIdAndUpdate that are wrong by default and bite everyone once.

new: true returns the document after the change. Without it you get the old one back and your API responds with stale data that looks like the update failed.

runValidators: true runs your schema rules on the update. Without it, an update can write a value that create would have rejected, and your rules only apply to new records.

the two options
const book = await Book.findByIdAndUpdate(id, patch, {
  new: true,            // return the updated document, not the old one
  runValidators: true   // apply schema rules to this update too
})

if(!book) throw ApiError.notFound('Book not found')
update operators
OperatorDoes
$setSet fields. Applied automatically to a plain patch object.
$unsetRemove a field entirely
$incAdd to a number (negative to subtract)
$push / $pullAdd to / remove from an array
$addToSetPush only if not already there

15 References and populate

Documents point at each other by storing an ObjectId plus a ref naming the model it belongs to. That is how a record remembers who owns it.

populate swaps the id for the actual document when you read. It costs an extra query, so populate what a response needs and nothing more.

Pass a second argument to choose fields: .populate('ownerId', 'name email'). Without it you pull the whole user document into every row of a list.

ref and populate
// In the schema
ownerId: {
  type: mongoose.Schema.Types.ObjectId,
  ref: 'User',
  index: true
}

// Reading without populate
book.ownerId        // ObjectId("6ad140c5...")

// Reading with it
const book = await Book.findById(id).populate('ownerId', 'name email')
book.ownerId.name   // "Ada Lovelace"

Part four: when it breaks

Mongoose errors are specific. Read the name before you change anything.

16 Errors you will meet

The first four have a correct HTTP status that is not 500. If any of them reaches a client as a 500, your error handler is missing a branch.

error → cause → status
ErrorCauseAnswer with
CastErrorA value will not convert — usually an id that is not 24 hex characters400
ValidationErrorA schema rule failed. err.errors holds one entry per bad field.400
MongoServerError code 11000Duplicate value on a unique index409
Result is nullNo document with that id404
MongooseError: Operation buffering timed outNever connected. The query waited for a connection that did not arrive.fix the connection
ECONNREFUSED 127.0.0.1:27017MongoDB is not runningstart it
Cannot read properties of nullYou used the result of findById without checking for null404
OverwriteModelErrormongoose.model() called twice with the same nameimport the model, do not redefine it
A field you sent is missing from the saved documentIt is not in the schema, so it was strippedadd it to the schema
find({ someVirtual: true }) matches nothingVirtuals are not in the database and cannot be queriedstore the field, or aggregate
handling the first three
if(err.name === 'CastError'){
  statusCode = 400
  message = `Invalid ${err.path}: ${err.value}`
}

if(err.name === 'ValidationError'){
  statusCode = 400
  message = 'Validation failed'
  details = Object.values(err.errors).map((e) => ({
    field: e.path, message: e.message
  }))
}

if(err.code === 11000){
  statusCode = 409
  message = `Duplicate value for: ${Object.keys(err.keyValue || {}).join(', ')}`
}

17 Quick reference

The commands worth keeping to hand, for when you want to look at the database directly rather than through your API.

mongosh
# Is it running at all?
mongosh --eval "db.runCommand({ping:1})"

# Open a shell on your database
mongosh mongodb://127.0.0.1:27017/your_db

# Inside the shell
show collections
db.books.countDocuments()
db.books.find({ genre: "fantasy" }).limit(5)
db.books.findOne()
db.books.getIndexes()
db.books.deleteMany({})          # empties the collection, no undo