Skip to content

GKozlowskiDesign/MongoDB-CMS-Backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MongoDB NodeJS CMS BackEnd

The motivation for this project was to help me write code more efficiently and to understand foundational concepts and standardized processes of using MongoDB in connection to ExpressJS and NodeJs.

Table of Contents

  1. Featured
  2. Technologies
  3. Architecture
  4. Authentication
  5. Categories
  6. Posts
  7. Users
  8. Contributions
  9. License
  10. Acknowledgments

Featured

  • I learned how to set up different types of Models such as Posts, Users, and Authentication
  • I learned more of the standardized processes of using MongoDB or NoSQL databases tools
  • I learned more about use of ExpressJS and NodeJS with a NoSQL database

Technologies

  • JavaScript: The primary programming language for implementing dynamic and interactive elements of the website.
  • ExpressJS: Express.js is a minimalistic and flexible Node.js web application framework. It simplifies building robust APIs and web applications by providing a set of features for routing, middleware, and handling HTTP requests and responses.
  • AWS MongoDB Cluster: An AWS MongoDB Cluster refers to a managed MongoDB database service offered by Amazon Web Services (AWS). It provides scalable, high-performance MongoDB databases in a cloud environment, allowing users to offload the operational aspects of database management while focusing on application development.
  • Mongoose: Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a convenient way to interact with MongoDB databases, defining schemas, models, and perform operations on data using a higher-level abstraction.
  • Nodemon: Nodemon is a tool used during Node.js development. It monitors for changes in your source code and automatically restarts your server, saving you from manually stopping and restarting the server after each code modification.
  • Bcrypt: A library to help you hash passwords. You can read about bcrypt in Wikipedia as well as in the following article: How To Safely Store A Password.
  • Multer: Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency.
  • Path: This is an exact copy of the NodeJS ’path’ module published to the NPM registry.

Architecture

The Model-Controller-Route (MCR) architecture is a design pattern commonly used in web applications, including those built with Node.js, Express.js, and NoSQL databases like MongoDB.

This architecture separates the concerns of your application into three main components:

Model: The model represents the data structures and the business logic of your application. In the context of MongoDB, the model typically corresponds to the schema that defines the structure of the documents you'll store in the database. In Node.js, you can use libraries like Mongoose to define and work with models. The model interacts directly with the database, handling data validation, retrieval, insertion, and updates.

Controller: The controller acts as an intermediary between the routes and the model. It contains the application's logic for processing requests, making decisions, and invoking methods on the model to interact with the database. Controllers handle tasks like data validation, authentication, and responding to client requests. Controllers are typically organized based on the routes they handle.

Routes: Routes define the endpoints and routes requests to the appropriate controller methods. In Express.js, you create routes using the Router object. Each route is associated with one or more HTTP methods (GET, POST, PUT, DELETE, etc.) and specifies a URL path. When a request matches a defined route, the corresponding controller method is executed.

mvc_express

Authentication

Description

This code is for a Node.js application using the Express.js framework to create two API routes for user registration and user login. It appears to be related to user authentication and is likely part of an authentication system for a web application.

User Registration Endpoint (/register):

  • When a POST request is made to /register, the code attempts to create a new user record in the database.
  • It generates a salt using bcrypt.genSalt and then hashes the user's password with the generated salt using bcrypt.hash.
  • It creates a new User instance with the provided username, email, and the hashed password.
  • It saves the new user to the database using newUser.save() and responds with a JSON representation of the newly created user if successful.
  • If there's an error during registration, it responds with a 500 internal server error and sends the error message.

User Login Endpoint (/login):

  • When a POST request is made to /login, the code attempts to authenticate a user.
  • It searches the database for a user with the given username using User.findOne.

Categories

Description

This code defines an Express.js API route for managing categories.

Category Creation (POST): When a POST request is made with JSON data containing a category name, it creates a new category using the provided data and saves it to the database. If successful, it responds with the saved category. If there's an error, it returns a 500 internal server error.

Fetching All Categories (GET): When a GET request is made to this route, it retrieves all categories from the database and responds with a JSON array containing the categories. If there's an error, it returns a 500 internal server error.


Post

Description

This code defines two API routes for managing posts within a Node.js application using Express.js

Create Post (POST): This route allows users to create a new post. When a POST request is made to the root URL ("/"), it creates a new Post object based on the data provided in the request's body. It then attempts to save this post to the database. If successful, it responds with the saved post data (HTTP 200). If there's an error, it responds with a 500 internal server error.

Update Post (PUT): This route is used to update an existing post identified by its ID. It first checks if the post's username matches the one provided in the request body, ensuring that only the original author can update the post. If it's the correct user, the route updates the post's data with the new content provided in the request body using Post.findByIdAndUpdate. It then responds with the updated post data (HTTP 200). If there's an error during either the authorization or the update process, it responds with a 500 internal server error or a 401 unauthorized error if the user is not authorized to update the post.

Description

This code defines two API routes for managing posts within a Node.js application using Express.js

Delete Post (DELETE): When a DELETE request is made to /id, the code first attempts to find the post by its ID using Post.findById. If the post is found, it checks if the username associated with the post matches the username provided in the request body for authorization. If authorized, it proceeds to delete the post using post.delete() and responds with a success message ("Post has been deleted!") and an HTTP status code of 200. If not authorized, it responds with a 401 unauthorized error. If there's an error during the deletion process, it responds with a 500 internal server error.

Get Post (GET): When a GET request is made to /id, the code attempts to find the post by its ID using Post.findById. If the post is found, it responds with the post data in JSON format and an HTTP status code of 200. If the post is not found, it responds with a 404 not found error.

These two routes allow users to delete their own posts (if authorized) and retrieve posts by their unique IDs.

Description

This code defines an API route for managing posts within a Node.js application using Express.js

GET All Posts ("/"): When a GET request is made to this route, it retrieves posts from the database. It can filter posts by two query parameters: username: If username is provided as a query parameter, it retrieves posts created by that specific user. catName: If catName is provided as a query parameter, it retrieves posts that belong to the specified category.


User

Description

This code defines an API route for managing a user account within a Node.js application using Express.js. These routes are used for user registration and authentication, ensuring secure password storage and authentication before granting access to user data.

User Registration (POST): This route handles user registration. When a POST request is made with user registration data (including username, email, and password), it does the following:

  • It generates a salt using bcrypt.genSalt(10) for password hashing security.It hashes the provided password with the generated salt using bcrypt.hash.
  • It creates a new User object with the provided username, email, and the hashed password.
  • It saves the new user to a database and responds with the user data (excluding the password) if successful (HTTP 200). If there's an error, it responds with a 500 internal server error

User Login (POST): This route handles user login. When a POST request is made with login data (username and password), it does the following:

  • It attempts to find a user in the database with the provided username using User.findOne.
  • If no user is found, it responds with a 400 bad request and an error message ("Wrong Credentials!").
  • If a user is found, it compares the provided password with the stored hashed password using bcrypt.compare.
  • If the passwords do not match, it responds with a 400 bad request and an error message ("Wrong Credentials!").
  • If the passwords match, it constructs a response object containing all user properties except the password (using destructuring and _doc) and responds with this user data (HTTP 200).
  • If there's an error during the login process, it responds with a 500 internal server error.

Contributing

Contributions to the Website are welcome! If you find any issues or have suggestions for improvements, please feel free to open an issue or submit a pull request.

License

This project is licensed under the MIT License.

Acknowledgments

The Website was developed by Gary Kozlowski.