Skip to content

Databases: MongoDB and Mongoose

Beginning of the lesson

Databases: MongoDB and Mongoose

Store, query, and shape real application data with a document database

Big Idea: Your Node apps have been keeping data in memory or in JSON files, which vanishes or gets messy as the app grows. A database stores data durably and lets you query it efficiently. MongoDB is a popular document database that stores data as JSON-like documents, and Mongoose is the Node library that gives those documents structure, validation, and a clean API.
By the end you will be able to:
  • explain what a document, a collection, and a database are in MongoDB;
  • connect a Node app to MongoDB and define a schema and model with Mongoose;
  • perform the four CRUD operations (create, read, update, delete);
  • judge when a document database fits a problem and when a relational one is better.

1. What is MongoDB? Documents and collections

MongoDB is a NoSQL document database. Instead of tables with fixed rows and columns, it stores documents: flexible, JSON-like objects. A group of related documents is a collection, and a group of collections is a database.

A single user document might look like this:

{
  "_id": "6512a3f0c1e4b2a9d8f00a12",
  "name": "Sara",
  "email": "sara@example.com",
  "age": 24,
  "hobbies": ["chess", "guitar"]
}

Notice the document holds an array (hobbies) directly inside it. In a relational database that usually needs a second table; in MongoDB it is just a field. Every document automatically gets an _id field, a unique identifier MongoDB generates for you (an ObjectId).

Analogy. Think of a relational (SQL) database as a strict spreadsheet: every row must have exactly the same columns, in the same order. A document database is more like a folder of index cards: each card is self-contained, can carry lists and nested notes, and two cards do not have to look identical. That flexibility is powerful, but it also means you are responsible for keeping the cards consistent.

Database: shopDB Collection: users { _id: ..., name: "Sara",   age: 24,   hobbies: ["chess","guitar"] } one document { _id: ..., name: "Alex",   email: "alex@ex.com" } a different shape is allowed Collection: orders { _id: ..., total: 42,   items: 3, paid: true } { _id: ..., total: 9,   items: 1, paid: false }
A database holds collections; a collection holds documents; each document is a self-contained JSON-like object.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers