CRUD with NodeJs, Express and MongoDB

Tram Ho

1. Environment settings

  • B1 : Create a project directory
  • B2 : Create package.json file – a file that manages dependencies installed locally. To create the package.json file, we need to initialize npm
  • B3 : Express installation
    • Express is a commonly used module included with Node.js. Express runs between the server created by Node.js and the frontend pages of a web application. Express also solves application routing, directing users to the right page based on user interaction with the application.
    • Although there are many options other than express, Express is the easiest to learn about the interaction between the Node.js and frondend backend.
    • Install express

  • B4 : Create the app.js file in the project directory

  • B5 : Start server

2. Building applications

In this article, we will build a CRUD Course application (add and edit courses)

1. Directory structure

  • You probably already know about the MVC model, in this example we will also build the application in the MVC model by separating the structure into separate parts depending on its function.
  • We will create 3 directories, models will contain code that interacts with the database, the controllsers directory contains the application’s logic that handles requests from clients and responses, and the route directory handles navigation.

2. Configure Application Entry Point (File app.js)

  • Install the dependencies

    • body-parser : To handle HTTP POST requests in express.js from version 4 and above, we need the body-parser middleware. The body parser extracts the entire body of incoming requests and displays them on req.body
    • mongoose : is an ODM (Object Data Modeling) library for MongDB and Node.js, which is used to convert objects (objects) in code into representations of these objects in MongoDB.
    • morgan : is a great logging tool when working with HTTP server in Node.js, is a middleware that allows us to easily log requests and errors to the console.
  • Import and set up dependencies
  • Set up mongoose: Use JavaScript promise to set up mongoose and catch errors.

    Note:

    • Best practice is to set the URI in .env and access the environment variables in the env file with process.env.VAR_NAME
    • You can install MongoDB on your computer or you can use the MongoDB Atlas cloud. To set up MongoDB Atlas and get the URI for your Database, you can refer to the instructions
  • Set up port, define route home and listen for port
  • Start server: Open the terminal, in the project directory, run:

    Results of connecting the database successfully and running the application at port 5035:

3. Create Model

  • First we will go into the example of creating Caurse. The application allows you to enter titles and descriptions for the created courses and courses that will be saved in MongoDB so that the client can access them when needed. The first model we create will be course.js in the models directory.
  • File course.js: First we import mongoose and define a schema

4. Create Controller

  • Create a course.js file in the controllers directory
  • Import mongoose and model course that we export when creating the model course.

  • Create a course: First we create a Course with the value corresponding to the keys in the courseSchema. Use the save () method of mongoDB to save data to the database. Return a promise that will return the response to the client if the save is successful and handle the error if an error occurs.

5. Create route

  • Create main.js file in routes routes.

    Note : Import express and createCourse from the controller

  • In the app.js fileWe import the route from the main.js file in the route directory. Set up the route with api prefix

6. Testing with Postman

So we have successfully created a new course and saved it into MongoDB.

7. Get list of courses

1. Controller

  • The course.js file is in the controllers directory

2. Route

  • The main.js file is in the route directory

3. Result

8. Get single course

1. Controller

  • The course.js file is in the controllers directory

2. Route

  • The main.js file is in the route directory

3. Result

9. Update course

1. Controller

  • The course.js file is in the controllers directory
  • Note: For the update of mongoDB we use the $ set operator

2. Route

  • The main.js file is in the route directory

3. Result

10. Delete course

1. Controller

  • The course.js file is in the controllers directory
  • Note: For the update of mongoDB we use the $ set operator

2. Route

  • The main.js file is in the route directory

Conclude

Share the news now

Source : Viblo