MongoDB & Mongoose Models
By the end of this lesson NoteNest will keep its notes in MongoDB, so they survive a restart. You will connect to the database when the server starts, describe a note with a Mongoose schema, send clean JSON with an id field, fill the database with sample data and add the indexes the API needs. The API contract from the last lesson does not change at all, so the Vue client will not notice the switch.
What you should know first: Build a REST API with Express 5. For MongoDB itself, see Databases, Collections & Documents and Mongoose Models & Validation, which cover queries, populate and middleware in depth. Versions checked: Mongoose 9.12.1 (with the MongoDB Node.js driver 7.8) against a MongoDB 9.0.2 server.
Documents, collections and models
MongoDB stores documents (JSON-like objects) inside collections (groups of similar documents), inside a database. NoteNest uses one database, notenest, with one collection, notes, for now.
MongoDB itself accepts any shape in a collection. Mongoose adds the rules on the Node.js side. You write a schema (the allowed fields, their types and checks) and turn it into a model, a class with methods such as find() and create(). Think of a bank's account-opening form: the form decides which boxes exist and which must be filled. The bank's almirah would hold any paper you push in, but the clerk only accepts papers on that form.
Step 1: Connect when the server starts
The connection string is already in server/.env as MONGODB_URI. Create server/src/db.js:
// server/src/db.js
import mongoose from 'mongoose'
export async function connectDB(uri) {
await mongoose.connect(uri, { serverSelectionTimeoutMS: 5000 })
const { host, name } = mongoose.connection
console.log(`MongoDB connected: ${name} on ${host}`)
}Then connect before listening, in server.js:
// server/src/server.js
import app from './app.js'
import { config } from './config.js'
import { connectDB } from './db.js'
await connectDB(config.mongodbUri)
app.listen(config.port, (error) => {
if (error) throw error
console.log(`NoteNest API listening on http://localhost:${config.port}`)
})Top-level await works in ES modules. Connecting first means the API never accepts requests it cannot answer. Our run printed:
MongoDB connected: notenest on 127.0.0.1 NoteNest API listening on http://localhost:3000
serverSelectionTimeoutMS: 5000 makes a missing database fail after 5 seconds instead of the default 30. We pointed the server at port 27099, where nothing was running, and it stopped with this line at the top of the error:
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27099
ECONNREFUSED means nothing is listening there. Check that MongoDB is running and the URI is right. A crash at start-up is the behaviour you want: a hosting platform sees it and restarts the server, instead of a half-working API answering every request with an error.
Step 2: The Note model
Create server/src/models/Note.js. Every rule here protects the data, whatever the client sends.
// server/src/models/Note.js
import mongoose from 'mongoose'
const noteSchema = new mongoose.Schema(
{
title: {
type: String,
required: [true, 'Title is required'],
trim: true,
maxlength: [120, 'Title can have at most 120 characters'],
},
body: {
type: String,
default: '',
maxlength: [10000, 'Body can have at most 10,000 characters'],
},
tags: {
type: [{ type: String, trim: true, lowercase: true, maxlength: 30 }],
default: [],
},
pinned: { type: Boolean, default: false, cast: 'Pinned must be true or false' },
},
{
timestamps: true,
toJSON: {
versionKey: false,
transform(doc, ret) {
const { _id, ...rest } = ret
return { id: _id.toString(), ...rest }
},
},
},
)
noteSchema.index({ pinned: -1, updatedAt: -1 })
noteSchema.index({ tags: 1 })
export const Note = mongoose.model('Note', noteSchema)What each part does:
required,maxlength: validators. The array form[value, message]replaces Mongoose's default message with one that is safe and friendly to show users.trimandlowercase: setters that clean values before saving." College "is stored as"college", so the tag filter does not miss notes because of a capital letter.cast: the message used when a value cannot be converted to the type, such aspinned: "maybe".timestamps: true: Mongoose adds and maintainscreatedAtandupdatedAt.toJSON: runs whenever Express callsres.json()on a document. It renames_idto anidstring and drops__v, Mongoose's internal version counter. This keeps the contract from the structure lesson: the client only ever seesid.mongoose.model('Note', ...): the model name is singular. Mongoose stores it in the plural, lowercase collectionnotes.
Here is the transform in action. We built a note in memory and printed it twice, first as a plain object, then as the JSON the client receives:
{
title: 'Revise Vue Router',
body: '',
tags: [ 'vue', 'college' ],
pinned: false,
_id: new ObjectId('6afa8dbd9ac45173e541dc59')
}
{"id":"6afa8dbd9ac45173e541dc59","title":"Revise Vue Router","body":"","tags":["vue","college"],"pinned":false}The input was title: ' Revise Vue Router ' and tags: ['Vue', ' College ']; the setters cleaned both. An ObjectId is MongoDB's default 12-byte id, shown as 24 hexadecimal characters. It is unique and created without asking the database. There is more about it in BSON Data Types & ObjectId.
Step 3: Swap the array for the model
Open routes/notes.js and replace the in-memory version. The paths and JSON shapes stay the same.
// server/src/routes/notes.js
import { Router } from 'express'
import mongoose from 'mongoose'
import { Note } from '../models/Note.js'
const router = Router()
function notFound(res) {
return res.status(404).json({ error: { code: 'NOT_FOUND', message: 'Note not found' } })
}
// GET /api/notes and GET /api/notes?tag=college
router.get('/', async (req, res) => {
const { tag } = req.query
const filter = typeof tag === 'string' ? { tags: tag.toLowerCase() } : {}
const notes = await Note.find(filter).sort({ pinned: -1, updatedAt: -1 }).limit(100)
res.json({ notes })
})
// GET /api/notes/:id
router.get('/:id', async (req, res) => {
const { id } = req.params
if (!mongoose.isObjectIdOrHexString(id)) return notFound(res)
const note = await Note.findById(id)
if (!note) return notFound(res)
res.json({ note })
})
// POST /api/notes
router.post('/', async (req, res) => {
const { title, body, tags, pinned } = req.body ?? {}
try {
const note = await Note.create({ title, body, tags, pinned })
res.status(201).json({ note })
} catch (err) {
if (err instanceof mongoose.Error.ValidationError) {
const message = Object.values(err.errors).map((e) => e.message).join('. ')
return res.status(400).json({ error: { code: 'VALIDATION_ERROR', message } })
}
throw err
}
})
export default routerThe routes are now async, because database calls take time. In Express 5, if an async handler throws or its promise rejects, Express passes the error to your errorHandler, which answers with a 500 and logs the details. That is why the POST route can simply throw err for anything that is not a validation error.
Three choices here protect the API:
- Sort and limit on the server.
sort({ pinned: -1, updatedAt: -1 })puts pinned notes first (true sorts above false when descending), then the newest.limit(100)stops one request from pulling the whole collection. - Check the id before querying. Without the check,
Note.findById('abc')throwsCastError: Cast to ObjectId failed for value "abc" (type string) at path "_id" for model "Note", and the client gets a 500. A malformed id is simply a note that does not exist, so it gets a 404. - Pick fields from the body.
Note.create(req.body)would let a client set any field the schema has, such ascreatedAt, and later fields such asowner. Naming the four allowed fields closes that hole, known as mass assignment.
Step 4: Seed sample data
A seed script fills a development database with known data, so everyone on the team starts from the same notes. Create server/src/seed.js:
// server/src/seed.js
import mongoose from 'mongoose'
import { connectDB } from './db.js'
import { Note } from './models/Note.js'
if (process.env.NODE_ENV === 'production') {
throw new Error('Refusing to seed a production database')
}
const samples = [
{ title: 'DBMS viva questions', body: 'Normal forms, keys, ACID', tags: ['College'], pinned: true },
{ title: 'Sunday groceries', body: 'Atta 5 kg, toor dal, curd', tags: ['home'] },
{ title: 'Train to Jaipur', body: 'PNR 4521378690, coach B2', tags: ['travel', 'home'] },
]
await connectDB(process.env.MONGODB_URI)
await Note.deleteMany({})
const notes = await Note.insertMany(samples)
console.log(`Seeded ${notes.length} notes`)
await mongoose.disconnect()Add the script with npm pkg set scripts.seed="node --env-file=.env src/seed.js" inside server/, then run it:
> server@1.0.0 seed > node --env-file=.env src/seed.js MongoDB connected: notenest on 127.0.0.1 Seeded 3 notes
The script deletes every note first, so the guard at the top matters: it refuses to run when NODE_ENV is production.
Step 5: Try the API again
Restart the server and repeat the calls from the last lesson. These are real responses from our run:
curl "http://localhost:3000/api/notes?tag=College"
curl http://localhost:3000/api/notes/abc
curl -X POST http://localhost:3000/api/notes -H "Content-Type: application/json" -d "{\"title\":\" Fees due 10 Dec \",\"tags\":[\" Exam \"],\"createdAt\":\"2001-01-01\"}"
curl -X POST http://localhost:3000/api/notes -H "Content-Type: application/json" -d "{\"body\":\"no title\",\"pinned\":\"maybe\"}"{"notes":[{"id":"6afa8c734da7997d42e1a368","title":"DBMS viva questions","body":"Normal forms, keys, ACID","tags":["college"],"pinned":true,"createdAt":"2026-11-16T04:54:11.222Z","updatedAt":"2026-11-16T04:54:11.222Z"}]}
{"error":{"code":"NOT_FOUND","message":"Note not found"}}
{"note":{"id":"6afa8c8975fc6a0ce194438b","title":"Fees due 10 Dec","body":"","tags":["exam"],"pinned":false,"createdAt":"2026-11-16T04:54:33.812Z","updatedAt":"2026-11-16T04:54:33.812Z"}}
{"error":{"code":"VALIDATION_ERROR","message":"Pinned must be true or false. Title is required"}}The tag College matched because the route lowercases it. The new note's title and tag were cleaned, and its createdAt is today, not 2001, because the route ignored that field. Stop and restart the server: the notes are still there.
One surprise to know about: Mongoose's Boolean type casts some strings. We sent "pinned": "yes" and the note was saved with pinned: true. Casting is helpful for form data but too forgiving for a JSON API, so CRUD Endpoints & Validation adds strict request validation before the data reaches Mongoose.
The page below renders the real list JSON the way the Vue client will, with Indian date formatting and the server's sort rule applied when you pin a note.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>NoteNest list from real API JSON</title>
<script src="https://cdn.jsdelivr.net/npm/vue@3.5.44/dist/vue.global.prod.js"></script>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; max-width: 34rem; }
li { margin-bottom: 10px; }
small { color: #555; }
button { margin-left: 6px; }
</style>
</head>
<body>
<div id="app">
<h1>My notes</h1>
<ul>
<li v-for="note in sorted" :key="note.id">
<strong>{{ note.pinned ? '[Pinned] ' : '' }}{{ note.title }}</strong>
<button type="button" @click="note.pinned = !note.pinned">{{ note.pinned ? 'Unpin' : 'Pin' }}</button>
<br>
<small>Tags: {{ note.tags.join(', ') }} | Created {{ formatDate(note.createdAt) }}</small>
</li>
</ul>
</div>
<script>
// Real response body of GET /api/notes from the lesson's run
const body = '{"notes":[{"id":"6afa8c734da7997d42e1a368","title":"DBMS viva questions","body":"Normal forms, keys, ACID","tags":["college"],"pinned":true,"createdAt":"2026-11-16T04:54:11.222Z","updatedAt":"2026-11-16T04:54:11.222Z"},{"id":"6afa8c734da7997d42e1a369","title":"Sunday groceries","body":"Atta 5 kg, toor dal, curd","tags":["home"],"pinned":false,"createdAt":"2026-11-16T04:54:11.228Z","updatedAt":"2026-11-16T04:54:11.228Z"},{"id":"6afa8c734da7997d42e1a36a","title":"Train to Jaipur","body":"PNR 4521378690, coach B2","tags":["travel","home"],"pinned":false,"createdAt":"2026-11-16T04:54:11.228Z","updatedAt":"2026-11-16T04:54:11.228Z"}]}';
const dateFormat = new Intl.DateTimeFormat("en-IN", {
dateStyle: "medium", timeStyle: "short", timeZone: "Asia/Kolkata"
});
Vue.createApp({
data() {
return { notes: JSON.parse(body).notes };
},
computed: {
sorted() {
// Same rule as the server: pinned first, then newest updatedAt
return this.notes.toSorted((a, b) =>
Number(b.pinned) - Number(a.pinned) || b.updatedAt.localeCompare(a.updatedAt));
}
},
methods: {
formatDate(iso) {
return dateFormat.format(new Date(iso));
}
}
}).mount("#app");
</script>
</body>
</html>MongoDB stores dates in UTC, shown with a Z at the end. The browser converts them to India time only for display, which is the right split: store UTC, format at the edge.
Indexes for the queries you run
An index is a sorted lookup structure, like the index at the back of a textbook, that lets MongoDB find documents without reading the whole collection. Add indexes for the queries your API actually runs. NoteNest's list query filters by tags and sorts by pinned and updatedAt, so the schema declares exactly those two. When the model starts, Mongoose creates them. We listed them with Note.listIndexes():
_id_: {"_id":1}
pinned_-1_updatedAt_-1: {"pinned":-1,"updatedAt":-1}
tags_1: {"tags":1}_id_ always exists. An index on an array field such as tags is a multikey index: MongoDB adds one entry per tag. Building indexes on a big collection takes time, so in production many teams turn off automatic index creation (Mongoose's autoIndex option) and create indexes as a planned step. Indexes and Query Plans with explain() show how to check that a query really uses one.
Common mistakes
- Listening before connecting. Requests arrive, queries wait or fail, and errors look random. Await
connectDB()first. - Sending
_idin some responses andidin others. Use onetoJSONtransform so every response follows the contract. Note.create(req.body). It lets clients set fields they should not. Pick the allowed fields.- Letting a bad id become a 500. Check with
mongoose.isObjectIdOrHexString()and return 404. - Running the seed script against production. Guard it with
NODE_ENV, and never keep production credentials in your local.env.
Interview questions
1. Why use Mongoose when MongoDB is schemaless?
The database accepts any shape, but the application still needs rules: required fields, types, lengths, defaults and clean values. Mongoose keeps those rules in one schema on the server, adds timestamps and JSON transforms, and gives a model API that is easier to read than raw driver calls.
2. How do you send id instead of _id to the front end?
Add a toJSON option to the schema with a transform that copies _id into an id string and removes _id and __v. Express calls toJSON through res.json(), so every route returns the same shape without repeating code.
3. What is mass assignment and how do you prevent it in an Express route?
It happens when a route passes the whole request body to the model, so a client can set fields such as role or owner that only the server should control. Prevent it by picking allowed fields explicitly, or by validating the body against a strict schema that strips unknown keys.
4. Which indexes would you add for NoteNest's list endpoint, and why?
A compound index on { pinned: -1, updatedAt: -1 } supports the sort, and an index on tags supports the tag filter. Indexes should match real queries, because each extra index costs disk space and slows down writes.
Key points
connectDB()indb.jsruns beforeapp.listen();serverSelectionTimeoutMSmakes a missing database fail fast.- The Note schema validates and cleans data with
required,maxlength,trim,lowercase, custom messages andtimestamps. - A
toJSONtransform turns_idintoidand hides__v, keeping the API contract unchanged. - Express 5 sends errors from
asyncroutes to the error handler; validation errors become 400, malformed ids become 404. - Pick allowed body fields to stop mass assignment, and keep query values plain strings to stop NoSQL injection.
- Seed development data with a guarded script, and add indexes that match your filters and sorts.
Exercise
Add a colour field to NoteNest notes so users can colour-code them. Allowed values: yellow, green, blue and pink, with yellow as the default. Invalid values must return a 400 error with the message "Colour must be yellow, green, blue or pink". Update the model, the POST route and the seed script (give the DBMS note green), then test one valid and one invalid request with curl.
Show solution
In models/Note.js, add the field next to pinned:
colour: {
type: String,
enum: {
values: ['yellow', 'green', 'blue', 'pink'],
message: 'Colour must be yellow, green, blue or pink',
},
default: 'yellow',
},In routes/notes.js, pick it from the body and pass it on: const { title, body, tags, pinned, colour } = req.body ?? {} and Note.create({ title, body, tags, pinned, colour }). Without this change Mongoose would never see the value, because the route picks fields. In seed.js, add colour: 'green' to the DBMS note and run npm run seed. A request with "colour":"pink" returns 201 with "colour":"pink", and "colour":"red" returns {"error":{"code":"VALIDATION_ERROR","message":"Colour must be yellow, green, blue or pink"}}. Notes created before the change have no stored colour, but Mongoose applies the default when it loads them, so the API still sends yellow.
Quick Quiz
1. Why does server.js await connectDB() before app.listen()?
Connecting first turns a missing database into a clear start-up failure.
2. What does the toJSON transform in the Note schema do?
It runs during res.json(), so every response uses the same shape.
3. A client sends GET /api/notes/abc. What does the NoteNest route return?
The route checks the id first, so a malformed id is treated as a missing note.
4. Which index best supports Note.find({ tags: 'home' })?
An index on an array field is a multikey index with one entry per element.
Learn MEVN Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
