본문 바로가기
데이터베이스

mongoose - express 모델 만들기

by 즐거운코딩 2023. 8. 5.
반응형

express 를 통한 데이터의 CRUD를 구현해 보고자 합니다.

간단한 예제로 농장의 가판대에서 파는 농작물 재고관리하는 앱을 만들어 봅니다.

일반적인 애플리케이션에서는 다양한 모델이 있을 수 있으므로 복잡하게 하나의 파일에서 관리하기 보다는 모델별로 나눠서 관리하는 것이 효율적 입니다.

 

1. 모델 만들기

models 디렉토리를 만들고, product.js 파일에 product 모델을 다음과 같이 만듭니다.

Schema 속성에 required 는 필수 입력 값으로 선언한 것이며, min 은 최소값, 카테고리는 세개를 선언하고, lowercase로 첫글자 대문자 입력을 제한합니다.  이와 같이 데이터 입력시 유효성을 확인할 수 있도록 합니다.

const mongoose = require("mongoose");

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
    min: 0,
  },
  category: {
    type: String,
    lowercase: true,
    enum: ["fruit", "vegetable", "dairy"],
  },
});

const Product = mongoose.model("Product", productSchema);

module.exports = Product;

 

2.  초기데이터 입력하기

처음에 데이터베이스에 값이 없기 때문에 개발을 위해 초기 데이터를 만들 필요가 있습니다. 

다음과 같이 seeds.js 를 만들어 별도의 웹서버 없이 바로 데이터베이스에 연결하여 샘플 데이터를 입력합니다.

초기에 한번만 작업한다고 생각하면 됩니다.

우선 데이터베이스에 연결하여 1개 데이터를 넣어 봅니다.

const mongoose = require("mongoose");
const Product = require("./models/product");

mongoose
  .connect("mongodb://127.0.0.1:27017/farmStand", { useNewUrlParser: true })
  .then(() => {
    console.log("mongo connection open !!!");
  })
  .catch((err) => {
    console.log("OH NO mongo connection error !!!");
    console.log(err);
  });

const p = new Product({
  name: "Ruby Grapefruit",
  price: 1.99,
  category: "fruit",
});
p.save()
  .then((p) => {
    console.log(p);
  })
  .catch((e) => {
    console.log(e);
  });

초기 데이터 입력하기

터미널에서 node seeds.js 로 단독 실행하면 mongo db 연결하여 'Ruby Grapefruit' 데이터를 입력합니다.

이제 mongo db에 저장된 것을 다음과 같이 확인해 봅니다.

mongo db 데이터 조회

show dbs : 현재 생성된 데이터베이스 목록 확인

use farmStand : 특정 데이터베이스 선택하기

show collections : 데이터베이스내 컬렉션 확인하기 , 현재 products 가 존재(product collection의 복수형)

db.products.find() : products내 저장된 데이터 확인하기

 

이제 mongoose의  insertMany 메서드를 이용해 여러 개의 데이터를 입력합니다.

insertMany 의 특성으로 입력할 데이터의 유효성 검사를 하여 하나라도 맞지 않으면 전체 데이터가 입력되지 않습니다.

const mongoose = require("mongoose");
const Product = require("./models/product");

mongoose
  .connect("mongodb://127.0.0.1:27017/farmStand", { useNewUrlParser: true })
  .then(() => {
    console.log("mongo connection open !!!");
  })
  .catch((err) => {
    console.log("OH NO mongo connection error !!!");
    console.log(err);
  });

// const p = new Product({
//   name: "Ruby Grapefruit",
//   price: 1.99,
//   category: "fruit",
// });
// p.save()
//   .then((p) => {
//     console.log(p);
//   })
//   .catch((e) => {
//     console.log(e);
//   });

const seedProducts = [
  {
    name: "Fairy Eggplane",
    price: 1.0,
    category: "vegetable",
  },
  {
    name: "Organic Goodness Melon",
    price: 4.99,
    category: "fruit",
  },
  {
    name: "Organic Mini Seedless Watermelon",
    price: 3.99,
    category: "fruit",
  },
  {
    name: "Organic Celery",
    price: 1.5,
    category: "vegetable",
  },
  {
    name: "Choloate Whole Milk",
    price: 2.69,
    category: "dairy",
  },
];

Product.insertMany(seedProducts)
  .then((res) => {
    console.log(res);
  })
  .catch((e) => {
    console.log(e);
  });

seeds.js 로 초기 데이터를 데이터베이스에 저장하기
mongo db에서 입력한 데이터 확인하기

이와 같이 모델을 만들어 초기 데이터까지 입력해봤습니다. 

실제 개발에서는 도중에 모델을 변경할 일이 생기게 되고 따라서 지금 입력한 seed 데이터도 변경을 해야하는 경우가 생깁니다.  때문에 모델 변경시에는 기존 데이터를 모두 삭제하고 변경된 모델에 맞도록 seed 파일을 변경하여 다시 데이터를 입력해야 합니다.

반응형