[ TIL ] - MongoDB / mongoose

Gorae·2021년 7월 27일
0

(TIL) Node.js

목록 보기
5/5
post-thumbnail

MongoDB

  • https://docs.mongodb.com/manual/administration/install-community
    (사이트에서 community edition 설치하면 됨)
  • MongoDB는 NoSQL이며, 데이터가 JSON 형태로 db에 저장됨.
  • 초보자들도 쉽게 다룰 수 있으며, 규칙이 적고 유연해서 많은 부분을 수정할 수 있음.
  • 설치 확인 : terminal 에서 mongod, mongo 순서대로 입력.
  • mongo명령어 실행 시 나오는 url 을 받아와야 함.

mongoose

  • Nodejs 를 위한 Object Modeling.
  • MongoDB 는 Javascript 로 만들어지지 않았기에, JS 와 연결하려면 어댑터가 필요함.
  • mongoose 는 MongoDB 를 Javascript 와 연결하는 어댑터 역할.
npm i mongoose // mongoose 설치

import mongoose from "mongoose"; // import

// terminal 창에서 mongo 명령 실행 시 나오는 "url/내가 설정할 폴더명" 넣기
mongoose.connect("url/폴더명"); // string으로 된 Database 를 요청

// mongoose 연결 확인
// on 은 여러 번 발생 가능
mongoose.connection.on("error", (error) => console.log("Error!", error));
// once 는 한 번만 발생 가능
mongoose.connection.once("open", () => console.log("Connected!"));

Model

  • Model 은 mongoose 를 import 하면 생성 가능.
  • Schmea 를 통해 Model 의 형식을 정의할 수 있음.(구체적일수록 좋다, 에러 방지 가능)
    예를 들어, Number 로 정의해 둔 곳에 String 값이 들어갈 경우, 정상적으로 생성되지 않는 것을 확인할 수 있음.
    https://mongoosejs.com/docs/guide.html
  • Model의 사용 : Model.find(), Model.findById() 등의 함수로 사용.
import mongoose from "mongoose";

// Schema 설정
const contentsSchema = new mongoose.Schema({
  title: { type: String, required: true }, 
  description: String, // String 은 {type: String} 을 간결하게 나타낸 것임
  hashtags: [{ type: String }],
  views: { type: Number, required: true },
}); 

// 미들웨어 위치

// Model 생성
// 여기서 mongoose.model()은 contentsSchema의 복사본이라 보면 됨
const Contents = mongoose.model("Contents", contentsSchema);

// Model export
export default Contents

Model 에서 미들웨어 사용

https://mongoosejs.com/docs/middleware.html

  • 미들웨어는 모델 생성 전에 위치해야 함.
// 미들웨어의 형태
schema.pre("save", async function(){});

// 예시 - save 전에 console.log()가 실행됨
contentsSchema.pre("save", async function(){
  console.log(this); // this 는 저장하려는 정보를 나타냄
});

생성된 데이터를 db에 저장하기

방법 1. save() 사용

const contents = new Contents({ 
  title, // title: title
  description, // description: description
  hashtags: hashtags.split(",").map((text)=>`#${text}`),
  views: 0,
});
await contents.save();

방법 2. Model.create() 사용

await Contents.create({ 
  title,
  description,
  hashtags: hashtags.split(",").map((text)=>`#${text}`),
  views: 0,
});
profile
좋은 개발자, 좋은 사람

0개의 댓글