Search Bar Module with MERN Stack
MERN 스택을 이용한 검색창 모듈 구현
* MERN Stack
- MongoDB, Express, React.js, Node.js로 조합된 기술스택을 의미한다.
Database | - MongoDB |
Front-End Side | - React Router - Axios & Bootstrap |
Back-End Side | - Node.js - Express (REST APIs) |
Overview (개요)
- 검색창에 아무런 입력이 없으면, 모든 Item을 출력한다.
- 사용자는 Title 속성 이름을 검색창에 입력하여 Item을 검색할 수 있다.
MERN Stack Architecture (아키텍처)
- Node.js Express exports REST APIs & Interacts with MongoDB Database using Mongoose ODM.
- React Client sends HTTP Requests and retrieves HTTP Responses using Axios, consumes data on the components.
- React Router is used for navigating to pages.
REST APIs
Methods | URLs | Actions |
GET | api/tutorials | get all Tutorials |
GET | api/tutorials/:id | get Tutorial by id |
POST | api/tutorials | add new Tutorial |
PUT | api/tutorials/:id | update Tutorial by id |
DELETE | api/tutorials/:id | remove Tutorial by id |
DELETE | api/tutorials | remove all Tutorials |
GET | api/tutorials?title=[kw] | find all Tutorials which title contains'kw' |
Node.js Web Server (웹 서버; 백엔드)
Project File Structure (파일 및 디렉토리 구조)
File | Description |
app/config/db.config.js | - Exports configuring parameters for MongoDB connection & Mongoose. |
server.js | - Configure CORS, initialize & run Express REST APIs. |
app/models/index.js | - Add configuration for MongoDB database. - Create Mongoose data model in tutorial.model.js. |
app/controllers/tutorial.controller.js | - Tutorial controller |
app/routes/tutorial.routes.js | - Routes for handling all CRUD operations (including custom finder) |
1. Create Directory
$ mkdir nodejs-express-mongodb
$ cd nodejs-express-mongodb
2. Initialize the Node.js APP
npm init
name: (nodejs-express-mongodb)
version: (1.0.0)
description: Node.js Restful CRUD API with Node.js, Express and MongoDB
entry point: (index.js) server.js
test command:
git repository:
keywords: nodejs, express, mongodb, rest, api
author: your_name
license: (ISC)
Is this ok? (yes) yes
3. Install Necessary Modules
npm install express mongoose body-parser cors --save
* Necessary Modules
Module | Description |
Express | - Building the REST APIs. |
Mongoose | - MongoDB object modeling for node.js. |
body-parser | - Helps to parse the request and create the req.body object. |
cors | - Provides Express middleware to enable CORS with various options. |
4. Setup Express Web Server
// server.js
- Create an Express APP, then add body-parser and cors middlewares using app.use() method.
- Notice that we set origin: http://localhost:8081.
- Define a GET route which is simple for test.
- Listen on port 8080 for incoming reuqests.
4-1. Run Web Server
- You could run the Web Server using command below:
node server.js
- You could check the output on your browser with URL: http://localhost:8080/ and you will see:
5. Configure MongoDB Database & Mongoose
5-1. Configuration
// app/config/db.config.js
5-2. Define Mongoose
// app/models/index.js
5-3. Define the Mongoose Model
// app/models/tutorial.model.js
module.exports = mongoose => {
var schema = mongoose.Schema(
{
title: String,
description: String,
published: Boolean
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const Tutorial = mongoose.model("tutorial", schema);
return Tutorial;
};
- MongoDB 데이터베이스의 tutorials Collection의 모델을 정의한다.
6. Create the Controller
* Mongoose Model에서 제공하는 CRUD Functions
Mongoose Function | Description |
object.save() | - Create a new tutorial |
findById(id) | - Find a tutorial by id |
find() | - Retrieve all tutorials |
findByIdAndUpdate(id, data) | - Update a tutorial by id |
findByIdAndRemove(id) | - Remove a tutorial |
deleteMany() | - Remove all tutorials |
find( {title: {$regex: new RegExp(title), $options: "i"} } ) | - Find all tutorial by title |
// app/controllers/tutorial.controller.js
const db = require("../models");
const Tutorial = db.tutorials;
// Create and Save a new Tutorial
exports.create = (req, res) => {
};
// Retrieve all Tutorials from the database.
exports.findAll = (req, res) => {
};
// Find a single Tutorial with an id
exports.findOne = (req, res) => {
};
// Update a Tutorial by the id in the request
exports.update = (req, res) => {
};
// Delete a Tutorial with the specified id in the request
exports.delete = (req, res) => {
};
// Delete all Tutorials from the database.
exports.deleteAll = (req, res) => {
};
// Find all published Tutorials
exports.findAllPublished = (req, res) => {
};
7. Define Routes
- When a client sends request for an endpoint using HTTP request (GET, POST, PUT, DELETE),
We need to determine how the server will response by setting up the routes.
* Routes
Route | HTTP Request |
/api/tutorials | - GET, POST, DELETE |
/api/tutorials/:id | - GET, PUT, DELETE |
/api/tutorials/published | - GET |
// app/routes/tutorial.routes.js
React.js Client (클라이언트; 프론트엔드)
React.js Front-end Structure
Component | Description |
Tutorial | - Has form for editing Tutorial's details based on :id |
TutorialsList | - Gets and displays Tutorials |
AddTutorial | - Has form for submission new Tutorial |
- These components call TutorialDataService methods which use Axios to make HTTP Requests and receive Reponses.
React Redux Structure
Project File Structure (파일 및 디렉토리 구조)
1. Setup React.js Project
npx create-react-app react-crud
2. Import Bootstrap to Ract CRUD App
* Install Command
npm install bootstrap
// src/App.js
3. Add React Router to React CRUD App
* Install Command
npm install react-router-dom
// src/index.js
4. Add Navbar to React CRUD App
// src/App.js
5. Initialize Axios for React CRUD HTTP Client
* Install Command
npm install axios
// src/http-common.js
6. Create Data Service
// services/tutorial.service.js
7. Create React Components/Pages
// src/components/...
8. Run React CRUD App
- You could run the Web Server using command below:
npm start
- You could check the output on your browser with URL: http://localhost:8080/
Reference: bezkoder; React.js + Node.js + Express + MongoDB example: MERN stack CRUD App; BezKoder (URL)