Connecting APIs with MySQL and MongoDB
# CHAPTER 11
Connecting APIs with MySQL and MongoDB
1. Introduction
A REST API without a database is just an expensive calculator; it cannot remember anything. To persist data permanently, Node.js must connect to an external database. Node.js is uniquely versatile because it works beautifully with both Relational databases (MySQL) and NoSQL databases (MongoDB). In this chapter, we will learn how to connect an Express API to a database, execute queries asynchronously, and return the real data as JSON.2. Learning Objectives
By the end of this chapter, you will be able to:-
Connect an Express API to a MySQL database using the
mysql2package.
-
Connect an Express API to MongoDB using the
mongoosepackage.
-
Execute basic database queries asynchronously using
async/await.
- Understand the difference between relational and document databases in Node.
3. Beginner-Friendly Explanation
Imagine your Node.js application is a factory manager.- MySQL is an Excel Spreadsheet. Data must fit perfectly into rows and columns. If you try to put a shoe into the "Hats" column, the spreadsheet rejects it.
- MongoDB is a Filing Cabinet. Data is stored in folders (Documents) as pure JSON objects. You can throw a shoe, a hat, and a receipt into the same folder, and MongoDB doesn't care. It is highly flexible.
Because Node.js naturally speaks JSON, it is best friends with MongoDB. However, for enterprise systems that require strict financial records, Node.js works perfectly with MySQL.
4. Database 1: MySQL Integration
To connect to MySQL, we use themysql2 package because it natively supports modern JavaScript Promises (allowing us to use async/await).
Step 1: Install
Step 2: Database Configuration (config/db.js)
Step 3: The MySQL Controller
5. Database 2: MongoDB Integration (Using Mongoose)
Writing raw MongoDB queries is tedious. Instead, we use an ODM (Object Data Modeling) library called Mongoose. Mongoose acts as a translator, allowing us to interact with MongoDB using JavaScript objects.Step 1: Install
Step 2: Database Configuration (config/db.js)
6. Defining a Mongoose Model
MongoDB is schema-less by nature. Mongoose forces a schema onto it so our API data stays predictable.models/User.js
7. The MongoDB Controller
Notice how much cleaner Mongoose is compared to raw MySQL strings!8. Backend Workflow: Connection Timing
Where do you connect to the database? You MUST connect to the database *before* you turn on the Express server. If your server is listening for traffic, but the database connection hasn't finished, the first 100 users will crash the app.In app.js:
9. Best Practices
-
Never Hardcode Credentials: Your database password (
root123) should NEVER be typed directly into your JavaScript files. You must use a.envfile (via thedotenvpackage) to hide credentials from GitHub. We will cover this heavily in the deployment and security chapters.
10. Common Mistakes
-
Forgetting
await: If you writeconst users = User.find();withoutawait, theusersvariable will not contain the database rows; it will contain a pending Promise. When you send it viares.json(), the user will receive a bizarre, empty object. Alwaysawaityour database queries!
11. Exercises
-
1.
Compare the process of querying a database using raw SQL (via
mysql2) versus using an ODM like Mongoose. What are the advantages of using Mongoose?
12. Coding Challenges
-
Challenge: Using Mongoose syntax, write the controller logic to find a single user by their ID, assuming the ID is passed in the URL parameters. Use the
User.findById()method.
13. MCQs with Answers
When building an Express API with MongoDB, what is the purpose of the mongoose package?
Why is it standard practice to establish the database connection *before* calling app.listen() in your app.js file?
14. Interview Questions
- Q: Explain why Node.js and MongoDB are frequently paired together (The MEAN/MERN stack). What is the underlying data format they share?
-
Q: Describe how you handle asynchronous errors in an Express controller that is querying a database. Why is the
try/catchblock critical?
15. FAQs
Q: Which database should I choose for my project? A: Use MySQL/PostgreSQL if your data is highly relational and structured (e.g., a Banking app where Accounts, Transactions, and Users must be strictly linked). Use MongoDB if your data is flexible, unstructured, or rapidly changing (e.g., a Social Media feed, IoT sensor data).16. Summary
In Chapter 11, we gave our API a memory. We explored the two dominant database paradigms: Relational (MySQL) and NoSQL (MongoDB). By utilizing themysql2 and mongoose packages, we executed asynchronous queries to retrieve, create, and format real, persistent data into JSON. Finally, we learned the critical architectural rule of initiating database connections prior to opening the server to internet traffic.