MongoDB & Mongoose

ToastEggsToast·2020년 12월 12일
0

TIL

목록 보기
7/15

MongoDB

MongoDB는 문서 지향적 NoSQL 데이터베이스이다.
RDMS의 record와 비슷한 개념의 Document를 가지는데, document는 JSON objects 형태의 Key-value 쌍으로 이루어진 데이터 구조로 구성된다.
Document는 _id 라는 고유한 값을 갖는다. 이 고유한 값은 시간, 머신id, 프로세스id, 순차 번호로 구성되며 값의 고유성을 보장한다.
document 내부에서는 _id 가 중복 될 일이 없다. 단, 다른 document와 교차하게 될 경우 굉장히 희소한 확률로(매우!!!!!!) 겹칠수가 있긴 하다.
Collection은 RDMS의 table과 유사한 개념으로, document의 집합으로 구성된다.

Mongoose

MongoDB ODM(Object Document Mapping) 라이브러리 중 하나로, 데이터 베이스 연결, 스키마 정의, 스키마에서 모델로 변환, 모델을 이용한 데이터 관리 등을 할 수 있게 도와준다.

MongoDB 연결하기

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});

schema 정의하기

const kittySchema = new mongoose.Schema({
  name: String
});

schema란 자료의 구조, 자료간의 관계를 뜻한다.
schema를 통해 모델을 만들 수 있다.

model 정의하기

const Kitten = mongoose.model('Kitten', kittySchema);

graphql-compose

graphql-compose provides a type registry with a bunch of methods for programmatic schema construction. It allows not only to extend types but also remove fields, interfaces, args.

graphql compose는 스키마 구축 및 필드, 인터페이스 등을 생성 및 제거까지 가능한 라이브러리이다. 몽고 디비, 몽구스 등과 함께 사용해 데이터의 생성, 제거 또는 확인 등을 편리하게 작성하고 사용할 수 있다.

graphql-compose-mongoose

몽구스 모델을 위한 graphql-compose.
yarn add graphql graphql-compose mongoose graphql-compose-mongoose를 통해 설치가 가능하다.

import mongoose from 'mongoose';
import { composeMongoose } from 'graphql-compose-mongoose';
import { schemaComposer } from 'graphql-compose';

const LanguagesSchema = new mongoose.Schema({
  ...
});
const UserSchema = new mongoose.Schema({
 ...
});

const User = mongoose.model('User', UserSchema);
const UserTC = composeMongoose(User);

schemaComposer.Query.addFields({
  userById: UserTC.mongooseResolvers.findById(),
  userByIds: UserTC.mongooseResolvers.findByIds(),
  userOne: UserTC.mongooseResolvers.findOne(),
  userMany: UserTC.mongooseResolvers.findMany(),
  userDataLoader: UserTC.mongooseResolvers.dataLoader(),
  userDataLoaderMany: UserTC.mongooseResolvers.dataLoaderMany(),
  userByIdLean: UserTC.mongooseResolvers.findByIdLean(),
  userByIdsLean: UserTC.mongooseResolvers.findByIdsLean(),
  userOneLean: UserTC.mongooseResolvers.findOneLean(),
  userManyLean: UserTC.mongooseResolvers.findManyLean(),
  userDataLoaderLean: UserTC.mongooseResolvers.dataLoaderLean(),
  userDataLoaderManyLean: UserTC.mongooseResolvers.dataLoaderManyLean(),
  userCount: UserTC.mongooseResolvers.count(),
  userConnection: UserTC.mongooseResolvers.connection(),
  userPagination: UserTC.mongooseResolvers.pagination(),
});

schemaComposer.Mutation.addFields({
  userCreateOne: UserTC.mongooseResolvers.createOne(),
  userCreateMany: UserTC.mongooseResolvers.createMany(),
  userUpdateById: UserTC.mongooseResolvers.updateById(),
  userUpdateOne: UserTC.mongooseResolvers.updateOne(),
  userUpdateMany: UserTC.mongooseResolvers.updateMany(),
  userRemoveById: UserTC.mongooseResolvers.removeById(),
  userRemoveOne: UserTC.mongooseResolvers.removeOne(),
  userRemoveMany: UserTC.mongooseResolvers.removeMany(),
});

이처럼 graphql-compose-mogoose에서 제공하는 다양한 메소드 등을 통해 직접 코드를 작성하지 않아도 DB에 정보를 추가, 변경 혹은 제거할 수 있다.

profile
개발하는 반숙계란 / 하고싶은 공부를 합니다. 목적은 흥미입니다.

0개의 댓글