Skip to content

Instantly share code, notes, and snippets.

@halitbatur
Created May 12, 2022 11:23
Show Gist options
  • Save halitbatur/4b641bd64249880151a83082f35cc5eb to your computer and use it in GitHub Desktop.
Save halitbatur/4b641bd64249880151a83082f35cc5eb to your computer and use it in GitHub Desktop.
Discussion about MVC, DB Schema 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.
@cbaksakal
Copy link

cbaksakal commented May 19, 2022

Israa, Lara, Hamza, Cengiz

1. What is the best/most common file structure for backend NodeJS projects?
I am not 100% sure about the answer of this question, but according to "newer" best practices, instead of structuring the project by technical role, it is accepted good practice to divide the solution by self-contained components.

2. What is the MVC architecture? Why we will be using it?
MVC - Model, View, Controller

MVC is an architectural pattern that separates logic into three parts.

Model is the data-related component. Objects, classes etc. -in short data- used for the program is handled inside Model component.
View is the component that includes elements about the UI.
Controller has the logic part. Controller use and manipulate the data in "Model" to add logic and create-modify the "View".

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.
CRUD - Create, Read, Update, Delete are the four basic operations of persistent storage.

const mongoose = require("mongoose");

const FoodSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
    lowercase: true,
  },
  calories: {
    type: Number,
    default: 0,
    validate(value) {
      if (value < 0) throw new Error("Negative calories aren't real.");
    },
  },
});

const Food = mongoose.model("Food", FoodSchema);

module.exports = Food;

const express = require("express");
const foodModel = require("../models/food");
const app = express();

app.get("/foods", async (request, response) => {
  const foods = await foodModel.find({});

  try {
    response.send(foods);
  } catch (error) {
    response.status(500).send(error);
  }
});

module.exports = app;

Resources

@khatibAmjad
Copy link

Team: Berk - Huzeyfa - Amjad

What is the best/most common file structure for backend NodeJS project?

Create a solid file structure with distinct rules.
Separate your business logic and api routes. This will give you distinct groups like Data Access Layer, Service Layer etc.
Make their own folder for configuration files and long scripts.

What is the MVC architecture? Why will we be using it?
Model View Controller is a software architectural pattern that involves the separation of the application logic into three interconnected elements: the Model, View, and Controller.
Model: the lowest level which is responsible for maintaining data.
View: generates the UI.
Controller: the component that enables the interconnection between the views and the model so it acts as an intermediary. The controller doesn’t have to worry about handling data logic, it just tells the model what to do. After receiving data from the model it processes it and then it takes all that information it sends it to the view and explains how to represent it to the user.

Advantages of MVC:

  • MVC architecture will separate the user interface from business logic
  • Components are reusable.
  • Easy to maintain.
  • Different components of the application in MVC can be independently deployed and maintained.
  • This architecture helpt to test components independently.
  1. What are the CRUD operations? add an example code of each CRUD operations in Mongoose.
    CREATE procedures: Performs the INSERT statement to create a new record.
    READ procedures: Reads the table records based on the primary keynoted within the input parameter.
    UPDATE procedures: Executes an UPDATE statement on the table based on the specified primary key for a record within the WHERE clause of the statement.
    DELETE procedures: Deletes a specified row in the WHERE clause.

Exampls:

Get: find
router.get('/findall', function(req, res) {
StudentModel.find(function(err, data) {
if(err){
console.log(err);
}
else{
res.send(data);
}
});
});

Get: finde one
router.get('/findfirst', function(req, res) {
StudentModel.findOne({StudentId:{$gt:185}},
function(err, data) {
if(err){
console.log(err);
}
else{
res.send(data);
}
});
});

Delete:
router.get('/delete', function(req, res) {
StudentModel.remove({StudentId:188},
function(err, data) {
if(err){
console.log(err);
}
else{
res.send(data);
}
});
});

Post:
router.post('/delete', function(req, res) {
StudentModel.findByIdAndDelete((req.body.id),
function(err, data) {
if(err){
console.log(err);
}
else{
res.send(data);
console.log("Data Deleted!");
}
});
});

@yamanrajab90
Copy link

Team Members : Dilara, Sara, Yaman.
Question 1: What is the best/most common file structure for backend NodeJS projects?
1- Organize your Files Around Features

├── product
| ├── index.js
| ├── product.js
| └── product.hbs
├── user
| ├── index.js
| ├── user.js
| └── user.hbs

so you can access related files faster.

in another hand, if you used this approach to understand how the product pages work, you have to open up three different directories

├── controllers
| ├── product.js
| └── user.js
├── models
| ├── product.js
| └── user.js
├── views
| ├── product.hbs
| └── user.hbs

2- Use a config Directory, to place your configuration files
3- Use scripts Directory, to store Long npm Scripts
4- Use a service layer to store business logic
5- Use Test Files for unit testing


Question 2: MVC is an architectural paradigm that divides an application into three logical components: model, view, and controller. Each of these components is designed to handle certain parts of application development. and it is used for developing scalable and flexible projects.

Question 4: What are the CRUD operations? add an example code of each CRUD operation in Mongoose.
Create, read, update, and delete (CRUD) is a computer programming acronym that refers to the four functions that are required to develop a persistent storage application: create, read, update, and delete.
Examples :

  • Create : app.post("/food", async (request, response) => { const food = new foodModel(request.body); try { await food.save(); response.send(food); } catch (error) { response.status(500).send(error); } });

  • Read: app.get("/foods", async (request, response) => { const foods = await foodModel.find({}); try { response.send(foods); } catch (error) { response.status(500).send(error); } });

  • Update : app.put("/food/:id", async (request, response) => { try { await foodModel.findByIdAndUpdate(request.params.id, request.body); await foodModel.save(); response.send(food); } catch (error) { response.status(500).send(error); } });

  • Delete : app.delete("/food/:id", async (request, response) => { try { const food = await foodModel.findByIdAndDelete(request.params.id); if (!food) response.status(404).send("No item found"); response.status(200).send(); } catch (error) { response.status(500).send(error); } });

Reference : https://coursework.vschool.io/mongoose-crud/ , https://www.digitalocean.com/community/tutorials/nodejs-crud-operations-mongoose-mongodb-atlas

@awiednoor
Copy link

Noor Awied, Muhammed Nur, Mehmet Baki, Irem Kurt

  1. What is the best/most common file structure for backend NodeJS projects?
    Controller:
    The controller folder should contain a route file for each data class in the system
    Service Layer:
    It is where the business logic live (the app’s core logic)
    Data Access Layer:
    This layer manage the access to the database and offer the service layer functions to access and manipulate the data.
    —-----------------------------------------------------------------------------
  2. What is the MVC architecture? Why we will be using it?
    Model–view–controller
    Organize the related program logic into three interconnected components
    It’s an ​​architecture pattern rather than a design pattern

Model:
Lowest level, responsible for maintaining data, connected to the database. It responds to the controller requests because the controller never talks to the database by itself

Controller:
enables the interconnection between the views and the model so it acts as an intermediary

View:
Data representation is done by the view component. It actually generates UI or user interface for the user.

Advantages:
Decreases repetition
Separates interface from logic which increases readability.
Modularity and Reusable components
separation creates easrier maintenance and testing of components
create a solid structure of our web application

Disadvantages
Insufficient for small applications.
-The inefficiency of data access.

—-------------------------------------------------------------------------------------
3.Explore defining a schema in Mongoose, you can refer to this for more information (no answer in the comments required).

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.It defines the structure of the document, default values, validators, etc.

import mongoose from 'mongoose';
const { Schema } = mongoose;

const blogSchema = new Schema({
title: String, // String is shorthand for {type: String}
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});

—-----------------------------------

  1. What are the CRUD operations? add an example code of each CRUD operations in Mongoose.
    CRUD stands for Create, Read, Update, Delete.

const mongoose = require("mongoose");

const FoodSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
lowercase: true,
},
calories: {
type: Number,
default: 0,
validate(value) {
if (value < 0) throw new Error("Negative calories aren't real.");
},
},
});

const Food = mongoose.model("Food", FoodSchema);

module.exports = Food;

—-----------------------------------

const express = require("express");
const foodModel = require("../models/food");
const app = express();

app.get("/foods", async (request, response) => {
const foods = await foodModel.find({});

try {
response.send(foods);
} catch (error) {
response.status(500).send(error);
}
});

module.exports = app;

—------------------------

// ...

app.post("/food", async (request, response) => {
const food = new foodModel(request.body);

try {
await food.save();
response.send(food);
} catch (error) {
response.status(500).send(error);
}
});

// ...

—--------------

// ...

app.patch("/food/:id", async (request, response) => {
try {
await foodModel.findByIdAndUpdate(request.params.id, request.body);
await foodModel.save();
response.send(food);
} catch (error) {
response.status(500).send(error);
}
});

// ...
—----------

// ...

app.delete("/food/:id", async (request, response) => {
try {
const food = await foodModel.findByIdAndDelete(request.params.id);

if (!food) response.status(404).send("No item found");
response.status(200).send();

} catch (error) {
response.status(500).send(error);
}
});

// ...

@khaldarov
Copy link

khaldarov commented May 19, 2022

Ezgi Okur, Hafiz Mhammadah, Adnan Khaldar

What is the best/most common file structure for backend NodeJS projects?

  • JSON

What is the MVC architecture? Why will we be using it?

  • The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller. Each of these components are built to handle specific development aspects of an application. MVC is one of the most frequently used industry-standard web development framework to create scalable and extensible projects.

What are the CRUD operations? add an example code of each CRUD operations in Mongoose.

  • The mongos instances route queries and write operations to the shards in a sharded cluster.
  • Creat, Read, Update, Delete
  • const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
  • new Query().read('primary')
  • Model.where({ _id: id }).update({ title: 'words' });
  • Character.deleteOne({ name: 'Eddard Stark' }, () );

@mohammadibrah
Copy link

mohammadibrah commented May 19, 2022

Teammates: Nilay, Rasha, Mohammad Ibrahim

What is the best/most common file structure for backend NodeJS projects?
there some rules to best orgnizing our nodejs project, we could put some here:
Rule 1 – Organize your Files Around Features, Not Roles
Rule 2 – Don’t Put Logic in index.js Files
Rule 3 – Place Your Test Files Next to The Implementation
Rule 4 – Use a config Directory
Rule 5 – Put Your Long npm Scripts in a scripts Directory

What is the MVC architecture? Why we will be using it?

Three Levels Of MVC Model :

  1. Model –
    This level is considered the lowest level when compared with the View and Controller. It primarily represents the data to the user and defines the storage of all the application’s data objects.

  2. Views –
    This level is majorly associated with the User Interface(UI) and it is used to provide the visual representation of the MVC model. In simpler terms, this level deals with displaying the actual output to the user. It also handles the communication between the user (inputs, requests, etc.) and the controller.

  3. Controller –
    This level takes care of the request handler. It is often considered as the brain of the MVC system- a link, so to speak, between the user and the system. The controller completes the cycle of taking the user output, converting it into desired messages, and passing them on to the views(UI).
    and we will use it to orgnize our nodejs structure
    Explore defining a schema in Mongoose, you can refer to this for more information (no answer in the comments required).
    Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

What are the CRUD operations? add an example code of each CRUD operations in Mongoose.
there are operations about Creating, Reading, Updating, Deleting documents in mongodb
Create ex.

router.get('/save', function(req, res) {
    var newStudent = new StudentModel({StudentId:101, 
        Name:"Sam", Roll:1, Birthday:2001-09-08});

    newStudent.save(function(err, data) {
        if(err) {
            console.log(error);
        }
        else {
            res.send("Data inserted");
        }
    });
});

Read ex.
r```
outer.get('/findall', function(req, res) {
StudentModel.find(function(err, data) {
if(err){
console.log(err);
}
else{
res.send(data);
}
});
});


Update ex.
`router.post('/update', function(req, res) {
    StudentModel.findByIdAndUpdate(req.body.id, 
    {Name:req.body.Name}, function(err, data) {
        if(err){
            console.log(err);
        }
        else{
            res.send(data);
            console.log("Data updated!");
        }
    });  
});
`
Delete ex.
``router.get('/delete', function(req, res) {
    StudentModel.remove({StudentId:188}, 
    function(err, data) {
        if(err){
            console.log(err);
        }
        else{
            res.send(data);
        }
    });  
});

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