반응형

NoSQL과 mongDB

mongoDB

대표적인 NoSQL로 대용량 데이터를 처리하기 좋게 만들어졌다.

데이터 구조화라는 사전작업 없이 데이터베이스를 바로 사용할 수 있다.

  • NoSQL : 자료간 관계에 초점을 두지 않고 유연하게 저장하는 데이터베이스이다.
  • RDB(관계형 데이터베이스): 자료들의 관계를 중심으로, SQL질의어를 사용하기 위해 데이터를 구조화해야 한다.

 

구성요소

데이터베이스: 하나 이상의 collection을 가질 수 있는 저장소

컬렉션: 하나 이상의 document가 저장되는 공간 (table과 유사)

다큐먼트: 저장되는 자료, 구조 제약 없이 유연하게 저장 가능하다. (row와 유사)

objectID : document에서 유일한 키 값. 난수가 자동으로 생성된다. (primary key와 유사)

 

 

 

 


Mongoose ODM

 

ODM (Object Data Modeling)

MongoDB의 collection에 집중하여 관리하도록 도와주는 패키지.

collection을 모델화하여, 관련 기능들을 쉽게 사용할 수 있도록 도와준다.

  • 연결관리 용이: node.js 드라이버 외에도 mongoose를 이용하면 연결관리를 돕는다.
  • 스키마 관리: code-level에서 스키마를 정의하고 관리하게 해준다.
  • populate : join을 제공하지 않아서 populate로 간단하게 구현 가능하다.

 

 

ODM 사용하기

 

1. 스키마 정의 : collection에 저장될 document의 스미카를 코드 레벨에서 관리할 수 있게 스키마를 정의한다.

//models/schemas/board.js

const { Schema } = require('mongoose');

const PostSchema = new Scchma(
    {
        title: Sting,
        content: String,
    },
    {
	timestamps : true, // 생성, 수정시간을 자동으로 기록해줌.
    }
);

 

2. 모델 생성 : 작성된 스키마를 mongoose에서 사용할 수 있는 모델로 만든다. 

Post라는 모델 생성

// model.index.js

const mongoose = require('mongoose');
const PostSchema = require('./schemas/board');
exports.Post = mongoose.model('Post', PostSchema);

 

3. 데이터베이스 연결 : connect 함수를 이용해 DB와 연결할 수 있다.

const mongoose = require('mongoose');
const { Post } = require('./models');

mongoose.connect('mongodb://localhost:27017/myapp');

 

4. 모델 사용 : CRUD 작업 수행 가능하다. 

 

  • 생성: create
// index.js

const { Post } = require('./models');

async function main() {
    const created = await Post.create({
        title: 'first title',
        content: 'second title',
    });

    const multipleCreated = await Post.create([
        item1,
        item2,
    ]);
}

 

  • 조회: find, findById, findOne
// index.js

const { Post } = require('./models');

async function main() {
    const listPost = await Post.find(query);	// return array
    const onePost = await Post.findOne(query);	// return document
    const postById = await Post.findById(id);	// return document
}

 

조회를 위한 쿼리

1. exact match는 { key : value }

2. range query는 $lt, $lte, $gt, $gte 사용

3. 다중 값으로 검색 $in

4. 다중 조건 검색 $or  ( 기본이 and )

Person.find({
	name : 'kyubum',		// exact match
    age : {
    	$lt: 20,			// less than
        $gte: 10,			// greate than equal
    },
    languages: {
    	$in: ['ko', 'en']		// in 다중 값으로 검색
    },
    $or: [				// 다중 조건 검색
        { status: 'ACTIVE' },	
        { isFresh: true }
    ],
});

 

  • 수정: updateOne, updateMany, findByIdAndUpdate, findOneAndUpdate
  1. update 관련 함수를 사용하여 Document를 수정
  2. find~ 함수들은 검색된 Document를 업데이트 반영하여 반환
  3. update는 $set op를 사용하여 Document를 통째로 변경하지 않음.
// update 관련 함수를 사용하여 Document를 수정
// find~ 함수들은 검색된 Document를 업데이트 반영하여 반환
// update는 $set op를 사용하여 Document를 통째로 변경하지 않음.

async function main() {

	const updateResult = await Post.updateOne(query, {...});

	const updateResults = await Post.updateMany(query, {...});

	const postById = await Post.findByIdAndUpdate(query, {...});

	const onePost = await Post.findOneAndUpdate(query, {...});
};

 

  • 삭제: deleteOne, deleteMany, findByIdAndDelete, findOneAndDelete
  1. delete 관련 함수를 사용하여 Document 삭제
  2. find~ 함수들은 검색된 Document를 반환해준다.
async function main() {

	const deleteResult = await Post.deleteOne(query);

	const deleteResults = await Post.deleteMany(query);

	const onePost = await Post.findOneAndDelete(query);

	const postById = await Post.findByIdAndDelete(query);
};

 

 

5. populate.js

  • populate를 사용하면 SQL의 join과 유사한 기능을 수행할 수 있다.
  • populate를 사용하기 위해서는 모델 생성시 사용한 이름으로 ref값을 제공해야 한다.
  • populate는 MongoDB의 기능이 아닌 Mongoose에서 특별히 제공해주는 함수이다.

document 안에 document를 담지 않고, objectId를 가지고 reference하여 사용할 수 있는 방법을 제공한다.

document에는 reference 되는 objectID를 담고, 사용할 때 populate하여 하위 document처럼 사용할 수 있게 한다.

// populate.js

const Post = new Schema({
	...
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    comments:[{
    	type: Schema.Types.ObjectId,
        ref: 'Comment',
    }],
});

const post = await Post
.find().populate(['user', 'comment']);

 

반응형

+ Recent posts