Welcome to today’s tutorial! In this session, we’ll walk through how to set up a Node.js project and integrate it with MongoDB, a NoSQL database. This guide is designed to help you get a basic project up and running, using MongoDB to store data and Node.js to handle the backend.
Prerequisites
Before we get started, make sure you have the following installed on your computer:
- Node.js and Node Package Manager.
- MongoDB: Install MongoDB or use a cloud service for a managed database.
- Code editor: Use any code editor you’re comfortable with (e.g., VS Code, Sublime Text).
Steps for Setting Up a Node.js + MongoDB Project from Scratch
Step 1: Initialize Your Node.js Project
-
Create a new directory for your project: Open your terminal or command prompt, and navigate to the directory where you want to create your project:
mkdir node-mongo-project cd node-mongo-project
- Initialize a new Node.js project: Run the following command to create a
package.json
file:npm init -y
Step 2: Install Required Packages
Next, we’ll install the packages we need for our project. You’ll need:
- Express: A minimal and flexible Node.js web application framework.
- Mongoose: A MongoDB object modeling tool designed to work in an asynchronous environment.
- dotenv: A zero-dependency module to load environment variables from a
.env
file.
Install these dependencies by running:
npm install express mongoose dotenv
Step 3: Set Up MongoDB
Using MongoDB locally: If you have MongoDB installed locally, you can start it by running:
mongod
-
Using MongoDB Atlas: If you don’t have MongoDB installed locally, you can use MongoDB Atlas. Set up a free-tier cluster and get your connection string from the Atlas dashboard.
Step 4: Set Up Project Structure
Now, let’s organize the project by creating the following folder structure:
node-mongo-project/ │ ├── models/ │ └── userModel.js │ ├── routes/ │ └── userRoutes.js │ ├── .env ├── app.js └── package.json
Step 5: Create the .env File
Create a .env
file in the root of your project. This file will store sensitive information, like your MongoDB URI, in a safe way. Here’s what it should look like:
MONGO_URI=your_mongodb_connection_string
Make sure to replace your_mongodb_connection_string
with your actual MongoDB connection string (from MongoDB Atlas or local MongoDB).