How to Install Node.js, MongoDB, and Build an API Using Express.js and Mongoose
Step 1: Setting Up the Environment
Install Node.js and MongoDB: Begin by installing Node.js and MongoDB on your system. Node.js will allow you to run JavaScript on the server, while MongoDB will provide the database backend for your application.
Open a Blank Folder in VS Code: Create a new, empty folder to organize your project files. Open this folder in Visual Studio Code (VS Code).
Open the Terminal: From within VS Code, open the terminal. This is where you'll enter commands to interact with your project.
Initialize a New Node.js Project: Run the command
npm init
in the terminal to create a new Node.js project. Follow the prompts to provide information about your project.Install Dependencies: Run the following commands to install the required dependencies:
npm i express mongodb mongoose npm i nodemon --save-dev
Install MongoDB Compass: MongoDB Compass is a GUI tool that allows you to interact with your MongoDB databases visually. Install it to simplify database management.
Step 2: Creating the Project Structure
Create Folders: Inside your project folder, create two folders named
models
androutes
.Create Model for Menu Items: Inside the
models
folder, create a JavaScript file namedmenu.js
. In this file, define a schema for your menu items using Mongoose. Here's a sample code snippet:const mongoose = require('mongoose'); const menuSchema = new mongoose.Schema({ name: { type: String, required: 'Please enter the item name', }, price: { type: Number, required: 'Please enter the item price', } }); module.exports = mongoose.model('menu', menuSchema);
Create Routes for API: Inside the
routes
folder, create a JavaScript file namedmenus.js
. In this file, set up routes using Express.js to handle various API requests. Here's an example of how you can structure your routes:const express = require('express'); const router = express.Router(); const Menu = require('../models/menu'); // Define API routes here module.exports = router;
Step 3: Building the API with Express.js and MongoDB
Create the Express App: In the root of your project folder, create a file named
index.js
. This is the entry point of your application. Set up the Express app, connect to the MongoDB database, and define middleware. Here's an example:const express = require('express'); const mongoose = require('mongoose'); const url = 'mongodb://localhost/menudb'; const app = express(); mongoose.connect(url, { useNewUrlParser: true }); const con = mongoose.connection; con.on('open', () => { console.log('Connected to the database...'); }); app.use(express.json()); const menuRoutes = require('./routes/menus'); app.use('/menus', menuRoutes); const PORT = 9000; app.listen(PORT, () => { console.log(`Server started on port ${PORT}`); });
Define API Routes: Open the
menus.js
file inside theroutes
folder. Define routes for handling GET, POST, PATCH, and DELETE requests. Here's an example:const express = require('express'); const router = express.Router(); const Menu = require('../models/menu'); router.get('/', async (req, res) => { try { const menus = await Menu.find(); res.json(menus); } catch (err) { res.send('Error from GET request: ' + err); } }); // Define other routes for POST, PATCH, and DELETE module.exports = router;
Step 4: Testing the API
Run the Server: In the terminal, use the command
nodemon index.js
to start the server. This will make your API accessible athttp://localhost:9000
.Use Postman for Testing: Download and open Postman, a popular tool for testing APIs. Create a new collection and add a GET request to
http://localhost:9000/menus/
. You should see an empty response, as there's no data yet.Create Menu Items: Add a POST request to the collection. In the request body, provide JSON data for a menu item
{ "name": "Laptop", "price": 200000 }
Send the request, and you should receive a JSON response containing the added menu item.
Edit and Delete: To edit a menu item, use a PATCH request with the item's ID in the URL. To delete an item, send a DELETE request with the ID. Example URLs:
- Edit:
http://localhost:9000/menus/63d79729e3834172bbe05578
- Delete:
http://localhost:9000/menus/63d79729e3834172bbe05578
- Edit:
Conclusion
Congratulations! You've successfully set up Node.js, MongoDB, and Express.js to build a basic API for managing menu items. This tutorial covered the essentials of creating routes, interacting with the database using Mongoose, and testing the API using Postman. With this foundation, you can now extend your project to include more features and functionality as needed. Happy coding!
Comments
Post a Comment