Episode 9 of 12
MongoDB Setup
Learn how to set up MongoDB, connect it to your Node.js application using Mongoose, and define data models.
Most real applications need a database. MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents — making it a natural fit for Node.js applications.
What is MongoDB?
- NoSQL database — No rigid table schemas like SQL databases
- Document-based — Data stored as JSON-like documents (BSON)
- Flexible schemas — Documents in the same collection can have different fields
- Great with Node.js — JavaScript objects map naturally to MongoDB documents
Setting Up MongoDB Atlas
MongoDB Atlas is a free cloud-hosted MongoDB service:
- Create an account at mongodb.com/atlas
- Create a new cluster (free tier available)
- Create a database user with password
- Whitelist your IP address
- Get your connection string
Mongoose — MongoDB ODM
Mongoose is an Object Data Modeling library that provides a clean way to interact with MongoDB:
npm install mongoose
const mongoose = require('mongoose');
const dbURI = 'your-mongodb-connection-string';
mongoose.connect(dbURI)
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.log(err));
Creating a Schema & Model
const Schema = mongoose.Schema;
const blogSchema = new Schema({
title: { type: String, required: true },
snippet: { type: String, required: true },
body: { type: String, required: true }
}, { timestamps: true });
const Blog = mongoose.model('Blog', blogSchema);
module.exports = Blog;
The schema defines the structure of your documents. The model provides methods to interact with the database (create, read, update, delete).