Building an Online Restaurant Service REST API with Node.js and MongoDB
Tags: javascript, restapi, postman, mongodb
Published: 2024-03-16 15:29:57

In the realm of modern dining experiences, online restaurant services have become a staple for convenience and accessibility. Imagine a scenario where you could manage product listings, handle orders seamlessly, and maintain a database of customer interactions—all through a robust and efficient REST API. This article will delve into creating such an API using Node.js, Express.js, and MongoDB.

## Understanding the Project

Our project centres around a hypothetical online restaurant service. Here are the key features it offers:

1. **CRUD Operations for Products:** Users can perform Create, Read, Update, and Delete operations on product information, including details like name, price, and description.

2. **Order Placement:** Customers can place orders for products, providing essential information such as their name, email, and selected items.

3. **Order Listing:** The API includes endpoints to list all orders placed within the system.

## Technologies Used

Before diving into the code, let's take a moment to understand the technologies powering our REST API:

- **Node.js:** This serves as our backend runtime environment, allowing us to execute JavaScript code outside the browser.

- **Express.js:** A minimalist web framework for Node.js, Express.js simplifies handling HTTP requests, defining routes, and managing middleware.

- **MongoDB:** A NoSQL database used to store both product and order data, offering flexibility and scalability.

- **Mongoose:** A MongoDB object modeling library for Node.js that streamlines interactions with the database, providing schema-based solutions.

- **RESTful Architecture:** Following REST principles ensures our API is designed for scalability, maintainability, and uniformity.

- **Git & GitHub:** Utilized for version control and collaborative development, making it easier to manage and track changes in the project.

## Setting Up the Project

To get started with our Online Restaurant Service REST API, follow these steps:

1. **Clone the Repository:** Clone the project repository to your local machine to access the codebase. [Click Here](https://github.com/manish7017/restaurant_service) 

2. **Install Node.js and npm:** Ensure Node.js and npm (Node Package Manager) are installed on your machine. These tools are essential for running JavaScript applications.

3. **Install Dependencies:** Navigate to the project directory in your terminal and run `npm install` to install all project dependencies listed in the `package.json` file.

4. **Start the Server:** Once dependencies are installed, start the server by running `node server.js` in the terminal. This command will launch the API and make it available for incoming requests.

5. **Testing with Postman:** Use tools like Postman to send requests to the API endpoints. You can perform CRUD operations on products, place orders, and list orders to test the functionality of the API thoroughly.

## Understanding the Code

Now, let's dissect the code snippets provided to gain a deeper understanding of how our Online Restaurant Service REST API is structured and implemented.

### Middleware Setup

We begin by importing necessary modules such as Express.js, body-parser for parsing incoming request bodies, cors for handling Cross-Origin Resource Sharing, and mongoose for MongoDB interactions.

```javascript
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");

const app = express();
const PORT = process.env.PORT || 3000;

app.use(bodyParser.json());
app.use(cors());
```

### MongoDB Connection

Next, we establish a connection to MongoDB using Mongoose, specifying the database URL (`mongodb://localhost:27017/restaurant_db`), and handling connection errors and successes.

```javascript
mongoose.connect("mongodb://localhost:27017/restaurant_db", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB connection error:"));
db.once("open", () => {
  console.log("Connected to MongoDB");
});
```

### Data Models

We define two data models using Mongoose schemas: `Product` for managing product information and `Order` for handling order details.

```javascript
const productSchema = new mongoose.Schema({
  name: String,
  price: Number,
  description: String,
});
const Product = mongoose.model("Product", productSchema);

const orderSchema = new mongoose.Schema({
  products: [{ type: mongoose.Schema.Types.ObjectId, ref: "Product" }],
  totalPrice: Number,
  customerName: String,
  customerEmail: String,
  createdAt: { type: Date, default: Date.now },
});
const Order = mongoose.model("Order", orderSchema);
```

### API Endpoints

Our API includes several endpoints for managing products and orders:

- **Product Operations:** Create a new product, retrieve all products, update a product, and delete a product.

```javascript
// New product
app.post("/products", async (req, res) => { /* ... */ });

// All products
app.get("/products", async (req, res) => { /* ... */ });

// Update a product
app.put("/products/:id", async (req, res) => { /* ... */ });

// Remove a product
app.delete("/products/:id", async (req, res) => { /* ... */ });
```

- **Order Operations:** Place a new order and retrieve order details.

```javascript
// Place an order
app.post("/orders", async (req, res) => { /* ... */ });

// Order details
app.get("/products", async (req, res) => { /* ... */ });
```

### Server Initialization

Finally, we start the server and listen for incoming connections on the specified port (`3000` by default).

```javascript
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
```

## Conclusion

In this article, we've explored how to build an Online Restaurant Service REST API using Node.js, Express.js, and MongoDB. By following the provided instructions and understanding the code snippets, you can create a robust API for managing products, processing orders, and maintaining a seamless dining experience for your customers. Happy coding!