- What is the best/most common file structure for backend NodeJS projects?
- What is the MVC architecture? Why we will be using it?
- Explore defining a schema in Mongoose, you can refer to this for more information (no answer in the comments required).
- What are the CRUD operations? add an example code of each CRUD operations in Mongoose.
Created
July 4, 2024 07:17
-
-
Save halitbatur/7ac212e06915b0fb0c4aade36c8a20e2 to your computer and use it in GitHub Desktop.
MVC and CRUD
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
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();