This guide will help you set up MongoDB Atlas, create a database, and configure it to connect to your application using environment variables.
- Go to MongoDB Atlas.
- Sign up if you don’t have an account, or Log in if you already have one.
- After logging in, you’ll be directed to the MongoDB Atlas dashboard.
- Click on New Project on the left or Create a New Project if it’s your first time.
- Name your project (e.g.,
MyProject
) and click Next.
- In your new project, select Build a Cluster.
- Choose the Shared option (this is free and suitable for small projects).
- Select a cloud provider and region. You can choose any region close to you.
- Click Create Cluster.
Note: MongoDB will take a few minutes to set up your cluster.
- While the cluster is being set up, click on Database Access in the left menu.
- Click on Add New Database User.
- Create a username and password for your database.
- Save these credentials securely, as you’ll need them later to connect.
- Set the User Privileges to “Read and Write to Any Database” (default).
- Click Add User.
- Go to Network Access in the left menu.
- Click Add IP Address.
- Select Allow Access from Anywhere for development.
- This setting is convenient for development. For production, it’s recommended to restrict access to specific IPs.
- Click Confirm.
- Once your cluster is ready, go back to the Clusters section in your project.
- Click Connect next to your cluster name.
- Choose Drivers to connect MongoDB to your application (e.g., Node.js, Python).
- After selecting Drivers, choose the driver for your project (e.g., Node.js) and the version you’re using.
- MongoDB will display a connection string that looks like this:
mongodb+srv://<username>:<password>@cluster0.mongodb.net/?retryWrites=true&w=majority
- Replace
<username>
and<password>
with the database user credentials you created earlier.
- In your project’s root directory, create a
.env
file (if you don’t already have one). - Add the following line to the
.env
file, replacingDB_URL
with your connection string:DB_URL=mongodb+srv://<username>:<password>@cluster0.mongodb.net/?retryWrites=true&w=majority
- Make sure to replace
<username>
and<password>
with your MongoDB database username and password.
Your .env
file might look like this:
DB_URL=mongodb+srv://yourUsername:[email protected]/?retryWrites=true&w=majority
SESSION_SECRET=your_session_secret
CLOUDINARY_CLOUD_NAME=your_cloudinary_cloud_name
CLOUDINARY_API_KEY=your_cloudinary_api_key
CLOUDINARY_API_SECRET=your_cloudinary_api_secret