Skip to content

Instantly share code, notes, and snippets.

@halitbatur
Created July 4, 2024 07:17
Show Gist options
  • Save halitbatur/7ac212e06915b0fb0c4aade36c8a20e2 to your computer and use it in GitHub Desktop.
Save halitbatur/7ac212e06915b0fb0c4aade36c8a20e2 to your computer and use it in GitHub Desktop.
MVC and CRUD

Discuss the points below with your teammates and add your answers below in the comments

  1. What is the best/most common file structure for backend NodeJS projects?
  2. What is the MVC architecture? Why we will be using it?
  3. Explore defining a schema in Mongoose, you can refer to this for more information (no answer in the comments required).
  4. What are the CRUD operations? add an example code of each CRUD operations in Mongoose.
@Tumelo2748
Copy link

Selepe Thinane
Mthokozisi Dhlamini @sthabiso-iv
Thabiso Makolana @thabiso-makolana

  1. Root directory:

package.json: Contains project metadata and dependencies.

node_modules: Installed dependencies from package.json.
public: Stores static files served directly (e.g., images, CSS).
Source code directory (often named src or app):

models: Represents data structures and interacts with the database.

controllers: Handles incoming requests, interacts with models and services.

routes: Defines API endpoints and maps them to controller functions.

middlewares: Reusable functions that process requests before reaching controllers (e.g., authentication, logging).

services: Handles complex business logic or interacts with external services.

utils: Utility functions used across the project.

config: Configuration files for database, server, etc.

index.js: Main application entry point.

  1. MVC's main idea is to separate concerns and divide responsibilities, which can make it easier to maintain and extend the application over time. It's commonly used to implement user interfaces, data, and controlling logic, and is especially popular for building web applications.
    we will be using it to build more full-fledged backend applications, we will be following the MVC pattern in our project files structure.


  2. CRUD stands for Create, Read, Update, and Delete, the fundamental operations for interacting with data in applications. Mongoose provides a powerful way to perform these operations on your MongoDB database.

  3. Create (C):

const newRecord = new ModelName({
  key1: value1,
  key2: value2,
});

newRecord.save()
  .then((result) => {
    console.log('New record created:', result);
  })
  .catch((error) => {
    console.error('Error creating new record:', error);
  });
  1. Read (R):
ModelName.find({ key: value })
  .then((result) => {
    console.log('Retrieved records:', result);
  })
  .catch((error) => {
    console.error('Error retrieving records:', error);
  });
  1. Update (U):
ModelName.updateOne({ _id: recordId }, { $set: { key: updatedValue } })
  .then((result) => {
    console.log('Record updated:', result);
  })
  .catch((error) => {
    console.error('Error updating record:', error);
  });
  1. Delete (D):
ModelName.deleteOne({ _id: recordId })
  .then((result) => {
    console.log('Record deleted:', result);
  })
  .catch((error) => {
    console.error('Error deleting record:', error);
  });

@Pumlanikewana
Copy link

Pumlanikewana commented Jul 4, 2024

Mpho Oganne
Simphiwe Ndlovu
Pumlani Kewana

A well-organized file structure for backend Node.js projects can greatly enhance readability, maintainability, and scalability. A widely accepted and scalable structure is based on the principles of separation of concerns and modularization.

├── src/
│ ├── controllers/
│ │
│ ├── models/
│ │
│ ├── routes/
│ │
│ ├── middlewares/
│ │
│ ├── services
│ │
│ ├── utils/
│ │
│ ├── config/
│ │
│ ├── app.js

├── tests/

├─ .env
├── gitignore
├──package.json
├─ package-lock.json
└─ README.md

MVC architecture helps you to organize your web application and make it more manageable. It allows you to separate business logic from presentation logic, which makes it very easy to add new features or change existing ones without affecting the whole application.

  1. CRUD - create, read , update and delete.

example 1:
Create

// lines of code ommitted

const User = mongoose.odel('user', userSchema);

// creating a new user (some code from external source, leetcode and chatgpt)

const createUser = async () = >
{

const newUser = new User ({
// details of users code ommitted for saving time
});

// error handling code omitted

createUser();

Read

const readUsers = async () => { const users = await User.find({ age: { $gte: 18 } });
console.log('Users:', users); }; readUsers();

Update

Delete

const deleteUserById = async (userId) => {
// wrap inside a try and catch error handling code omitted

const deletedUser = await user.findByIdAndDelete(userId);

deleteUserById('...'); // user id goes here.

const User = mongoose.model('User', userSchema); // Update a user const updateUser = async () => { const updatedUser = await User.findByIdAndUpdate( '60c72b2f9b1e8b001c8e4b6c', { age: 26 }, { new: true } ); updateUser();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment