Working with MongoDB from Node.js

MongoDB Fundamentals — Working with MongoDB from Node.js
MongoDB Fundamentals
Chapter 8 · Working with MongoDB from Node.js

🟢 Working with MongoDB from Node.js

Every prior chapter used mongosh directly. This final chapter connects it all to real application code — exactly the kind of connection the Node.js course's database-integration chapter (node2-5) covered for MySQL, now applied to MongoDB.

The Native Driver: mongodb

Installing npm install mongodb gives you MongoClient, which connects using the exact same connection-string format Chapter 2 introduced:

Connecting from Node.js

const { MongoClient } = require("mongodb"); const client = new MongoClient("mongodb://localhost:27017"); await client.connect(); const db = client.db("shop");

CRUD from the Native Driver

The driver's methods map almost directly onto the mongosh commands from Chapters 3–4 — same method names, called from JavaScript instead of typed interactively:

Insert and Find, in Real Code

const products = db.collection("products"); await products.insertOne({ name: "Laptop", price: 899 }); const cheapItems = await products.find({ price: { $lt: 50 } }).toArray(); // .toArray() — the exact step Chapter 3's cursor gotcha said you'd need here

Mongoose: An ODM Layer on Top

Mongoose is an Object Document Mapper — it adds JavaScript-level schemas, models, and validation on top of the native driver. Where Chapter 6's $jsonSchema enforces structure at the database level, Mongoose enforces it at the application level, alongside convenience features like default values and pre/post hooks:

Defining a Mongoose Schema and Model

const mongoose = require("mongoose"); const productSchema = new mongoose.Schema({ name: { type: String, required: true }, price: { type: Number, min: 0 } }); const Product = mongoose.model("Product", productSchema); await Product.create({ name: "Notebook", price: 3.50 });

Native Driver vs. Mongoose

Native Driver

Closer to raw MongoDB, less abstraction, more manual — a good fit for smaller apps or when you want full control.

Mongoose

Application-level schema validation, models, and hooks — convenient for larger apps with many collections needing consistent structure.

Connection Pooling: Connect Once, Reuse

A MongoClient instance already manages an internal connection pool — the same underlying idea as the connection pooling covered for MySQL in node2-5. Create the client once when the application starts, and reuse it for every request; don't create a new client inside each individual route handler.

💻 Coding Challenges

Challenge 1: Connect and Insert

Write the Node.js code (using the native driver) to connect to a local MongoDB instance, select a database called library, and insert one document into a books collection.

Goal: Practice the connect → select database → operate sequence.

→ Solution

Challenge 2: Write a Mongoose Schema

Write a Mongoose schema and model for a Task with a required title (String) and a done field (Boolean, defaulting to false).

Goal: Practice Mongoose's schema syntax, including a default value.

→ Solution

Challenge 3: Fix a Connection-Per-Request Anti-Pattern

An Express route handler creates a new MongoClient and calls .connect() inside every single request. Explain what's wrong with this and how to fix it.

Goal: Practice applying this chapter's connection-pooling guidance to a concrete anti-pattern.

→ Solution

⚠️ Gotcha: Reconnecting on Every Request

It's an easy mistake to write new MongoClient(...) and await client.connect() directly inside a route handler, since that's the simplest thing that works in a quick test. Under real traffic, this means every single request pays the full cost of establishing a brand-new connection (and its internal pool) from scratch, and can quickly exhaust available connections on the MongoDB server under any real load. Create the client once — typically at application startup — and reuse that same client instance across every request; the driver's internal connection pool is designed to be shared, not recreated per request.

🎉 Course Complete

That's the full MongoDB Fundamentals course — from the document model through CRUD, schema design, data types, indexing, and finally real application code. Next up: MongoDB Intermediate/Advanced, covering the aggregation framework, schema design patterns at scale, transactions, replication, sharding, and a capstone data-modeling project.