본문으로 바로가기

[Node.js] Express+MongoDB, API 서버 구현하기(1)

category Web/Node.js 2020. 4. 1. 20:11

'Node.js 교과서 - 조현영 저'를 활용해 공부했습니다.


0. 목표

사용자 정보를 등록, 조회하고 특정 사용자에 해당하는 댓글을 조회, 등록, 수정, 삭제가능하게 서버를 구현하고

간단하게 뷰를 구현해 웹으로 확인해본다.

목표 화면ㅇㅅㅇ

1. API 구성

1) Users

유형 라우트 설명
GET /users 전체 사용자 정보 조회
POST /users 사용자 추가

2) Comments

유형 라우트 설명
GET /comments/:id id 사용자의 댓글 목록 조회
POST /comments 댓글 추가
PATCH /comments/:id ObjectId가 일치하는 댓글 수정
DELETE /comments/:id ObjectId가 일치하는 댓글 삭제

2. 스키마 모델링

User and Comment

3. 프로젝트 생성하기

$ express learn-mongoose --view=pug

생성된 프로젝트로 이동해 모듈 설치

$ cd learn-mongoose && npm i

mongoose를 활용해야 하므로 mongoose 설치

$ npm install mongoose

루트 디렉토리에 schemas폴더 추가, 이 폴더 내부에 MongoDB와 연결하고 스키마를 정의하는 파일들이 위치하게 됩니다.

디렉토리 구조

위와 같은 디렉토리 구조가 완성됩니다.

4. MongoDB 연결하기

schemas 폴더 안에 index.js 파일을 생성합니다.

/schemas/index.js

const mongoose = require('mongoose');

module.exports = () => {
  const connect = () => {
    if (process.env.NODE_ENV !== 'production') {
      mongoose.set('debug', true);
    }
    mongoose.connect('mongodb://[이름]:[비밀번호]@localhost:27017/admin', {
      dbName: 'nodejs',
    }, (error) => {
      if (error) {
        console.log('몽고디비 연결 에러', error);
      } else {
        console.log('몽고디비 연결 성공');
      }
    });
  };
  connect();
  mongoose.connection.on('error', (error) => {
    console.error('몽고디비 연결 에러', error);
  });
  mongoose.connection.on('disconnected', () => {
    console.error('몽고디비 연결이 끊겼습니다. 연결을 재시도합니다.');
    connect();
  });
};

처음 몽고디비를 설치한 후 설정해두었던 이름과 비밀번호로 접속합니다.

위의 코드에서는 이전 MongoDB 시작하기 포스팅에서 만들어 둔 nodejs 데이터베이스를 활용하게 됩니다.

5. Schema 생성

위에 모델링한것가 동일하게 스키마를 구성합니다.

(_id의 경우 기본으로 생성되는 고유한 ObjectId 값이기 때문에 따로 작성해 줄 필요가 없습니다.)

/schemas/user.js

const mongoose = require('mongoose');

const {Schema} = mongoose;
const userSchema = new Schema({
    name: {
        type: String,
        required: true,
        unique: true,
    },
    age: {
        type: Number,
        required: true,
    },
    married:{
        type: Boolean,
        required: true,
    },
    comment: String,
    createdAt:{
        type: Date,
        default: Date.now,
    },
});

module.exports = mongoose.model('User',userSchema);

마지막 줄에 model을 모듈화해 사용할 수 있도록 해줍니다.

/schemas/comment.js

const mongoose = require('mongoose');

const { Schema } = mongoose;
const {Types: {ObjectId}} = Schema;
const commentSchema = new Schema({
    commenter: {
        type: ObjectId,
        required: true,
        ref: 'User',
    },
    comment:{
        type: String,
        required: true,
    },
    createdAt: {
        type: Date,
        default: Date.now,
    },
});

module.exports = mongoose.model('Comment', commentSchema);

/schemas/index.js 의 하단에 구성한 모델을 추가해줍니다.

  ...
  
  require('./user');
  require('./comment');
};

 

'Web > Node.js' 카테고리의 다른 글

[Node.js] Express 구조 이해하기  (0) 2020.03.15
[Node.js] Express 시작하기  (0) 2020.03.15
[Node.js] http모듈 활용 - REST API와 라우팅  (0) 2020.03.14
[Node.js] Node.js란?  (0) 2020.03.12