본문 바로가기

MongoDB

Node js [mongoose-crud 만들기]

몽고DB자체에는 스키마를 지정하는 기능이 없지만 몽구스 라이브러리를 사용하면 스키마를 지정할  수 있다.

 

 

 

1. 스키마 

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

// 스키마 객체생성
const personSchema = new Schema({
  name: String,
  age: Number,
  email: { type: String, required: true },
});

module.exports = mongoose.model("Person", personSchema);

스키마 객체를 생성하고 module.exports로 PersonSchema 스키마객체를 내보낸다.
 
 
 
2. 몽구스 CRUD

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const Person = require("./hello-express");

mongoose.set("strictQuery", false);

const app = express();
// bodyParser.json() 미들웨어를 추가해야 HTTP에서 Body를 파싱할 수 있다.
app.use(bodyParser.json());
app.listen(3000, async () => {
  console.log("Server started");
  const mongodbUri =
    "mongodb+srv://id:password@cluster정보/test2?retryWrites=true&w=majority";

// 몽고DB 연결
  mongoose
    .connect(mongodbUri, { useNewUrlParser: true })
    .then(console.log("Connected to MongoDB"));
});

// 모든 person 데이터 찾아서 출력
app.get("/person", async (req, res) => {
  const person = await Person.find({});
  res.send(person);
});

// 특정 이메일로 person찾기
app.get("/person/:email", async (req, res) => {
  const person = await Person.findOne({ email: req.params.email });
  res.send(person);
});

// person 데이터 추가
app.post("/person", async (req, res) => {
  const person = new Person(req.body);
  await person.save();
  res.send(person);
});

// person 데이터 수정
app.put("/person/:email", async (req, res) => {
  const person = await Person.findOneAndUpdate(
    { email: req.params.email },
    { $set: req.body },
    { new: true }
  );
  console.log(person);
  res.send(person);
});

// person데이터 삭제
app.delete("/person/:email", async (req, res) => {
  await Person.deleteMany({ email: req.params.email });
  res.send({ success: true });
});

 스키마 객체를 불러와서 bodyParser.json() 미들웨어를 추가해 http Body에 파싱을 하고 몽고 DB을 연결을 한다. 그리고  GET, POST, PUT, DELETE 요청

 

2-1. 수정 요청사항에서 하나만 수정하는 경우에는 findOneAndUpdate()를 사용 

2-2. 여러개를 동시에 수정하는 경우에는 updateMany()를 사용 
 
 
 
3. GET, POST, PUT DELETE 요청

@server = http://localhost:3000

### GET 요청보내기
GET {{server}}/person 

### POST 요청보내기
POST {{server}}/person
Content-Type: application/json

{
  "name": "Hongsun2",
  "age": 28,
  "email": "Hongsun2@test.com"
}

### 생성한 문서 확인
GET {{server}}/person/Hongsun2@test.com

### PUT 요청보내기,문서 수정
PUT {{server}}/person/Hongsun2@test.com
Content-Type: application/json

{
  "age": 45
}

### 문서삭제
DELETE {{server}}/person/Hongsun2@test.com

VS코드 익스텐션에서 rest client설치해줘야 사용할 수 있다. 각 요청에 ###을 붙이면 send Request요청 버튼이 생성된다.
 
 

GET 요청 실행화면

 

PUT 수정 요청 실행화면

 

// person데이터 삭제
app.delete("/person/:email", async (req, res) => {
  await Person.deleteMany({ email: req.params.email });
  res.send({ success: true });
});

 

DELETE 삭제 요청 실행화면

 

DELETE가 성공하면 success:true가 뜬다.
 
 
https://www.yes24.com/Product/Goods/118379776

 

Node.js 백엔드 개발자 되기 - 예스24

- 자바스크립트 Node.js 백엔드 개발자가 되고 싶다면- HTML/CSS/자바스크립트 그다음에 꼭 보세요실력을 갖춘 개발자로 성장하려면 시작이 중요합니다. 그래서 이 책은 무엇부터 익혀야 하는지 막

www.yes24.com

 

'MongoDB' 카테고리의 다른 글

MongoDB 연산자 모음  (0) 2024.01.19
Node js mongoDB CRUD  (0) 2024.01.18