How to Install Node.js, MongoDB, and Build an API Using Express.js and Mongoose

How to Install Node.js, MongoDB, and Build an API Using Express.js and Mongoose

If you're looking to develop a powerful backend for your web application, you'll need to set up a robust environment that includes Node.js, MongoDB, and Express.js. In this guide, we'll walk you through the step-by-step process of installing these tools and creating a basic API using Express.js and Mongoose, which is a popular MongoDB ODM (Object-Document Mapping) library. Let's dive in!

Step 1: Setting Up the Environment

  1. 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.

  2. 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).

  3. Open the Terminal: From within VS Code, open the terminal. This is where you'll enter commands to interact with your project.

  4. 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.

  5. Install Dependencies: Run the following commands to install the required dependencies:

    npm i express mongodb mongoose npm i nodemon --save-dev
  6. 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

  1. Create Folders: Inside your project folder, create two folders named models and routes.

  2. Create Model for Menu Items: Inside the models folder, create a JavaScript file named menu.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);
  3. Create Routes for API: Inside the routes folder, create a JavaScript file named menus.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

  1. 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}`); });
  2. Define API Routes: Open the menus.js file inside the routes 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

  1. Run the Server: In the terminal, use the command nodemon index.js to start the server. This will make your API accessible at http://localhost:9000.

  2. 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.

  3. 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.

  4. 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

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