Creating a node server and REST API's for a dress store.

  • We can initiate a new project as an npm package using the command 'npm init'. This will create a package.json file to store the project configurations and the dependencies that we will download.

  • The next step would then be installing the necessary modules for example: express, mongoose, nodemon and cors.

After doing this then we can create a node.js app by setting up the express web server.

Code documentation

  1. const express = require("express");

    • This line imports the "express" module, which is a web framework for Node.js. It provides tools and features to simplify building web applications and APIs.
  2. const mongoose = require("mongoose");

    • This line imports the "mongoose" module, which is an Object Data Modeling (ODM) library for MongoDB and Node.js. It simplifies interacting with MongoDB databases by providing a higher-level abstraction.
  3. const app = express();

    • This line creates an instance of the Express application. You'll use this app object to define routes, middleware, and start the server.
  4. const wayRoute = require("./routes/Way");

    • This line imports the "wayRoute" module, which presumably defines routes related to some aspect of a "Way" in the application. The actual implementation of these routes is likely present in the "Way" module.
  5. app.use(express.json());

    • This line adds middleware to the Express application. Specifically, it's configuring the app to parse incoming JSON data from requests and make it available in the req.body object.
  6. mongoose.connect("mongodb://127.0.0.1:27017/DressStore");

    • This line connects the application to a MongoDB database located at "127.0.0.1" (localhost) on port 27017. The database's name is "DressStore". This establishes a connection that the application can use to interact with the MongoDB database.
  7. app.use("/api/suggest", wayRoute);

    • This line sets up a middleware that directs requests starting with "/api/suggest" to be handled by the wayRoute module that was imported earlier. This likely means that the wayRoute module defines specific routes for suggestions related to a "Way" in the application.
  8. const PORT = 4000;

    • This line defines a constant variable PORT with the value 4000. This is the port number on which the server will listen for incoming requests.
  9. app.listen(PORT, () => {

    • This line starts the Express server and makes it listen on the specified PORT.
  10. console.log(server is running on port ${PORT});

    • This line prints a message to the console indicating that the server is running and listening on the specified port.

So, in summary, this code sets up an Express web server, connects it to a MongoDB database, defines routes related to suggestions using the wayRoute module, and starts the server to listen on port 4000.

Creating a model

  1. const mongoose = require('mongoose');

    • This line imports the Mongoose library, which is an Object Data Modeling (ODM) library for MongoDB and Node.js. Mongoose simplifies interactions with MongoDB by providing an abstraction layer that allows you to define schemas, models, and perform various database operations using JavaScript.
  2. const productSchema = new mongoose.Schema({ ... });

    • This section defines the schema for the product data. A schema defines the structure and attributes of the documents that will be stored in the MongoDB collection.

    • name: A required field of type String. This represents the name of the product.

    • description: A field of type String. This represents the description of the product.

    • price: A required field of type Number. This represents the price of the product.

    • published: A Boolean field that represents whether the product is published or not.

    • category: A field of type String with an enum (enumeration) constraint. This means that the value of category must be one of the specified values: 'men', 'women', or 'teens'.

  3. module.exports = mongoose.model('New', productSchema);

    • This line exports a Mongoose model based on the defined schema. A Mongoose model is a constructor that provides an interface for interacting with the MongoDB collection associated with the schema.

    • 'New': This is the name of the collection that will be created in the MongoDB database to store the product documents. It's important to note that collection names in MongoDB are usually in lowercase and plural form, so 'news' might be a more conventional name for the collection.

    • productSchema: This is the schema that the model will use. The model provides methods for CRUD operations (Create, Read, Update, Delete) on the specified collection.

So, the code essentially creates a Mongoose schema for products, defines the attributes of a product, and exports a Mongoose model that can be used to interact with the MongoDB collection for products in a structured and organized manner.

Routes

const router = require("express").Router();
  • This line imports the Router class from the express module. The Router class allows you to create modular, mountable route handlers for your Express application.
javascriptCopy codeconst New = require("../models/New");
const Product = require("../models/New");
  • These lines import the New and Product models from the ../models/New file. These models likely define the schema and functionality for interacting with your MongoDB database.
javascriptCopy coderouter.post('/products', async (req, res) => {
  try {
    const newProduct = new Product(req.body);
    const product = await newProduct.save();
    res.status(200).json(product);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});
  • This is a route handler for a POST request to the /products endpoint. It receives data from the request body, creates a new instance of the Product model, saves it to the database, and then sends a JSON response containing the saved product. If there's an error during the process, it sends a 500 status code with an error message.
javascriptCopy coderouter.put('/:name', async (req, res) => {
  // ...
});
  • This is a route handler for a PUT request to the /name endpoint, where :name is a URL parameter. It checks if the provided product name matches the name in the request parameters. If it does, it updates the corresponding product using the New.findOneAndUpdate method. The updated product is then returned in the response.
javascriptCopy coderouter.get('/Products', async (req,res)=>{
  // ...
});
  • This is a route handler for a GET request to the /Products endpoint. It retrieves all products from the database using the New.find() method and sends a JSON response containing the products. If there's an error, it sends a 500 status code with an error message.
javascriptCopy coderouter.get('/:id', async (req, res)=>{
  // ...
});
  • This is a route handler for a GET request to the /:id endpoint, where :id is a URL parameter representing a product ID. It retrieves a product from the database using the New.findById method based on the provided product ID. If the product doesn't exist, it sends a 404 status code with a "Product Not Found" message.
javascriptCopy coderouter.delete('/product', async (req, res)=>{
  // ...
});
  • This is a route handler for a DELETE request to the /product endpoint. It deletes all products from the database using the New.deleteMany() method. If products are deleted, it sends a success message; otherwise, it sends a 404 status code with a "No products found" message.
javascriptCopy coderouter.delete('/:id', async (req, res)=>{
  // ...
});
  • This is a route handler for a DELETE request to the /:id endpoint, where :id is a URL parameter representing a product ID. It deletes a product from the database using the New.findByIdAndDelete method based on the provided product ID. If the product doesn't exist, it sends a 404 status code with a "Product Not Found" message.
javascriptCopy codemodule.exports = router;
  • This line exports the router instance, which contains all the defined routes and their corresponding handlers. This allows other parts of the application to use these routes by importing this module.