Débutant25 min de lecture

MongoDB & Mongoose Setup

Install MongoDB, connect with Mongoose ODM, and understand documents, collections, and the MongoDB data model.

What is MongoDB?

MongoDB is the most popular NoSQL database in the world. It is a document-oriented database, meaning it stores data as flexible, JSON-like documents instead of rows in rigid tables. Launched in 2009, MongoDB has become the go-to database for JavaScript developers because its document format maps naturally to JavaScript objects — you store and retrieve data in the same shape you work with it in your code.

Internally, MongoDB stores documents in BSON (Binary JSON), a binary-encoded serialization of JSON-like objects. BSON extends JSON with additional data types like Date, ObjectId, and Binary, while also being more efficient for storage and scanning. However, when you interact with MongoDB through code, you work with regular JavaScript objects — the BSON conversion happens automatically behind the scenes.

Documents are organized into collections, and collections live inside a database. A single MongoDB server can host multiple databases. The hierarchy is: Server > Database > Collection > Document. For example, a blogging application might have a database called blogapp containing collections called users, posts, and comments, each filled with individual documents.

Unlike SQL databases, MongoDB does not enforce a schema by default. Documents in the same collection can have completely different fields. One user document might have an address field while another does not — and that is perfectly fine. This flexibility is one of MongoDB's greatest strengths during rapid development, though in production you typically add validation rules to maintain some structure.

MongoDB has a generous free tier through MongoDB Atlas, their cloud-hosted service. You can create a free cluster that supports up to 512 MB of storage — more than enough for learning, prototyping, and small applications. This means you can start building with MongoDB right now without installing anything on your computer.

MongoDB Data Model

Understanding MongoDB's data model is essential before you start writing any code. The hierarchy goes: Database > Collections > Documents.

A document is the basic unit of data in MongoDB. It is essentially a JSON object with key-value pairs. Every document automatically receives a unique _id field — an ObjectId that MongoDB generates. This _id serves the same purpose as a primary key in SQL databases. A document can contain strings, numbers, booleans, arrays, nested objects, dates, and even binary data. Here is an example:

json
{
  "_id": "507f1f77bcf86cd799439011",
  "name": "Alice Johnson",
  "email": "alice@example.com",
  "age": 28,
  "hobbies": ["coding", "hiking"],
  "address": {
    "city": "Paris",
    "country": "France"
  },
  "createdAt": "2024-01-15T10:30:00Z"
}

A collection is a group of related documents — think of it as the MongoDB equivalent of a SQL table. Naming convention is lowercase and plural: users, posts, comments, orders. Unlike SQL tables, collections do not enforce any structure. You can have a user document with 5 fields next to one with 15 fields.

A key design choice in MongoDB is embedding vs referencing. In SQL, you use separate tables and JOIN them. In MongoDB, you have two options: embed related data directly inside the document (putting the address object inside the user document) or reference another document by its _id (storing authorId: "507f..." in a post document). The rule of thumb is: embed data that is always accessed together, reference data that is accessed independently or shared by many documents.

What is Mongoose?

While you can interact with MongoDB directly using its native driver (mongodb npm package), most Node.js developers use Mongoose — an ODM (Object Document Mapper) that sits on top of the native driver and adds powerful features.

The native MongoDB driver is low-level. You write raw queries, manually validate data, and handle all the structure yourself. Mongoose adds a layer of abstraction that makes working with MongoDB more organized and productive. Here is what Mongoose provides:

Schemas — Define the structure of your documents with types, defaults, and validation rules. While MongoDB itself does not enforce structure, Mongoose does at the application level. This gives you the flexibility of NoSQL with the safety of defined structures.

Models — Constructor functions compiled from schemas that give you an interface for CRUD operations. Instead of writing raw MongoDB queries, you use intuitive methods like User.find(), User.create(), User.findByIdAndUpdate().

Validation — Built-in and custom validators that check your data before it reaches the database. Required fields, string length limits, number ranges, regex patterns, custom validation functions — all defined in your schema.

Type Casting — Mongoose automatically converts values to the type defined in your schema. If your schema says age is a Number and someone passes the string "25", Mongoose casts it to the number 25.

Middleware (Hooks) — Run functions before or after certain operations (before saving, after deleting). Perfect for hashing passwords before save, or sending a notification email after a new user is created.

Query Building — Chain methods to build complex queries in a readable way: User.find({ age: { $gte: 18 } }).sort({ name: 1 }).limit(10).select('name email').

Install Mongoose with: npm install mongoose. It automatically installs the MongoDB native driver as a dependency.

Connecting to MongoDB with Mongoose

javascript
const mongoose = require('mongoose');

// --- Connection String Format ---
// Local:  mongodb://localhost:27017/myapp
// Atlas:  mongodb+srv://username:password@cluster.mongodb.net/myapp
//
// Parts: protocol://host:port/database-name
// Default MongoDB port is 27017

// --- Basic Connection ---
async function connectDB() {
  try {
    await mongoose.connect('mongodb://localhost:27017/myapp');
    console.log('Connected to MongoDB successfully!');
  } catch (error) {
    console.error('MongoDB connection error:', error.message);
    process.exit(1); // Exit if database connection fails
  }
}

connectDB();

// --- Connection Events ---
// Mongoose emits events you can listen to
mongoose.connection.on('connected', () => {
  console.log('Mongoose connected to MongoDB');
});

mongoose.connection.on('error', (err) => {
  console.error('Mongoose connection error:', err);
});

mongoose.connection.on('disconnected', () => {
  console.log('Mongoose disconnected');
});

// --- Graceful Shutdown ---
// Close the connection when the app stops
process.on('SIGINT', async () => {
  await mongoose.connection.close();
  console.log('MongoDB connection closed (app termination)');
  process.exit(0);
});

// --- With Environment Variable (recommended) ---
// In .env file:  MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/myapp
// In code:
// require('dotenv').config();
// mongoose.connect(process.env.MONGODB_URI);

MongoDB Atlas — Cloud Database

MongoDB Atlas is MongoDB's fully managed cloud database service. It handles all the infrastructure — server provisioning, backups, security patches, scaling — so you can focus on building your application. For learning and small projects, the free tier (M0 Shared) is perfect.

Here is how to set up Atlas step by step:

1. Create an Account — Go to mongodb.com/atlas and sign up for a free account. No credit card required for the free tier.

2. Create a Cluster — A cluster is a group of servers that store your data. Choose the free M0 tier, select a cloud provider (AWS, Google Cloud, or Azure), and pick a region close to you for lower latency. Click "Create Cluster" and wait a few minutes for it to provision.

3. Create a Database User — In the Security section, create a user with a username and password. This is separate from your Atlas account — it is the credentials your application uses to connect to the database. Use a strong, unique password.

4. Whitelist Your IP Address — MongoDB Atlas blocks all connections by default. You need to add your IP address to the whitelist (Network Access). For development, you can add 0.0.0.0/0 to allow connections from anywhere, but for production, restrict it to your server's IP.

5. Get Your Connection String — Click "Connect" on your cluster, choose "Connect your application," and copy the connection string. It looks like: mongodb+srv://username:password@cluster0.abc123.mongodb.net/myapp

6. Use Environment Variables — Never hardcode your connection string in your code. Store it in a .env file: MONGODB_URI=mongodb+srv://... and access it with process.env.MONGODB_URI. Add .env to your .gitignore so it never gets committed to version control.

Atlas also provides a web interface called Atlas UI where you can browse your databases, view documents, run queries, and monitor performance — very useful for debugging during development.

What does ODM stand for in the context of Mongoose?

Prêt à pratiquer ?

Crée ton compte gratuit pour accéder à l'éditeur de code interactif, lancer les défis et suivre ta progression.