Databases: MongoDB and Mongoose
Store, query, and shape real application data with a document database
- 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.