본문 바로가기
Databases/MongoDB | Mongoose

[Mongoose] 몽구스 시작하기 | INSERT | INSERT MANY

by CodeMia 2021. 11. 19.

지금까지 mongodb 데이터 베이스에 데이터 입력하는 법을 배웠다. 

이 mongodb 데이터 베이스를 서버와 연결하려면 2 가지 옵션이 있다. 

 

첫 번째는 그냥 몽고디비(mongodb native driver)를 사용하는 것이고,

두 번재는 몽구스(mongoose)를 사용하는 것이다. 

많은 개발자들이 몽구스를 더 선호한다.

이유는 몽구스 코드가 더 쉽고 간단하기 때문이다. 

 

몽구스 문서보기 

https://mongoosejs.com/

 


 

native mongodb driver로 몽고디비와 서버 연결하기 (비추)

native mongodb driver를 사용해서

mongodb와 서버와 연결하려면 아래와 같은 코드가 필요하다.

여기서 db를 입력하는 코드들을 아래 입력한다. 

입력 코드는 생략하도록 하겠다.

 

 

그럼 이제 방금 만든 fruits db를 지우고 나서 

새롭게  mongoose로 fruits db를 생성해 보자. 

 


 

데이터베이스 지우기 

1. 터미널에서 mongod 서버를 실행한다.

mongod 

 

2. 새 터미널 탭열어 mongosh을 열어 여기서 작업한다.

mongo 

 

3. 데이터 베이스 뭐 있나 보기 

show dbs 

 

4. fruitsDB로 이동 

use fruitsDB 

 

5. fruitsDB 지우기 

db.dropDatabase() 

 

6. fruits db 지워졌나 확인하기 

show dbs 

fruitsDB 지워졌음

 


 

Mongoose 란?

 

Mongoose를

Object Document Mapper (ODM) 이라고 부릅니다. 

 

ODM이란?

ODM은 object와 document를 1대1 매칭한다는 뜻인데요. Object는 자바스크립트의 데이터이고, Document는 몽고DB의 데이터입니다. 즉, document를 DB에서 조회하면 자바스크립트 object로 바꿔서 보여주는 역할이라고 생각하시면 됩니다. 

 

몽구스 장점

몽구스의 장점을 꼽자면 강제 스키마(schema)의 부활, populate, 프로미스와 콜백 사용 가능, 편리한 쿼리 빌더 등을 꼽을 수 있습니다. 

schema populate는 조금 재밌습니다.

schema: 사실 nosql 자체가 테이블과 join이 없는 것을 활용하는 DB입니다. 그런데 몽구스는 오히려 그 기능을 부활시켰습니다. DB에 다큐먼트를 넣을 때 값과 타입 그리고 필드를 검사합니다.

populate: SQL의 join과 비슷한 기능을 흉내 냅니다. 이럴거면 nosql을 왜 쓰냐고 하시겠지만, 실제로 몽고DB를 사용하다보면 황당하게도 schema와 join이 필요한 경우가 생깁니다. 그 때 이 기능이 필요합니다.

 

프로미스 콜백을 자유자재로 전환할 수 있다는 것은 정말 편리합니다.

노드는 지금 프로미스가 거의 공식 비동기 API처럼 되어있습니다. 기본 몽고DB가 콜백 기반이기 때문에 프로미스를 사용할 수 있게 해주는 몽구스가 참 고맙습니다.

몽고DB에서 쿼리를 작성할 때 JSON 형식으로 작성하기 때문에 뭔가 장황한 느낌을 줍니다. 몽구스의 쿼리는 간결한 느낌입니다. 제공하는 쿼리 빌더로 손쉽게 쿼리를 만들어줍니다

 

-자료 출처-

https://www.zerocho.com/category/MongoDB/post/5963b908cebb5e001834680e

 


 

Mongoose로 mongodb와 서버 연결하기 

 

1. 터미널에서 fruits 파일에 들어가서 npm으로 mongoose를 다운로드 한다. 

npm i mongoose 

 

 

2. mongoose로 mongodb와 서버 연결하기 / app.js 에서 

위에서 여러 줄 걸리던 것이 2줄이면 끝. 

 

콘솔에서 에러가 없어지고 < 모양이 사라지면 ctrl + C 로 나간다. 

 

 


Mongoose 용어 정리 

Collections

‘Collections’ in Mongo are equivalent to tables in relational databases. They can hold multiple JSON documents.

Documents

‘Documents’ are equivalent to records or rows of data in SQL. While a SQL row can reference data in other tables, Mongo documents usually combine that in a document.

Fields

‘Fields’ or attributes are similar to columns in a SQL table.

Schema

While Mongo is schema-less, SQL defines a schema via the table definition. A Mongoose ‘schema’ is a document data structure (or shape of the document) that is enforced via the application layer.

Models

‘Models’ are higher-order constructors that take a schema and create an instance of a document equivalent to records in a relational database.

 

-자료 출처-

https://www.freecodecamp.org/news/introduction-to-mongoose-for-mongodb-d2a7aa593c57/

 

 


mongoose로 데이터 넣기 

 

1. app.js에서 사과 1개 정보를 넣어보자.

 

line 4  새 schema 만들기. 구조 설정 

스키마: 앞으로 입력한 데이터들의 구조물 역할 (blueprint, structure )

nosql 특성 상 아무 정보를 입력해도 다 받아줄 수가 있기 때문에 

들어오는 데이터를 필요한 것만 받도록 걸러주는 것이 필요하다. 

collection 안의 데이터가 어떤 구조물인지 자바스크립트 오브젝트로 큰 골격을 잡아준다scaffold out 

 

 

line 5,6,7

이제 데이터베이스에 추가되는 새 fruit document는 이 구조 안에 들어가게된다. 

 

 

line 10 schema를 이용해서 Mongoose Model(collection 또는 table)을 만든다. 

 

1. model 첫 번째 파라미터: "Fruit"

위 schema에 적용되는 collection(table)의 이름.

fruits collection을 만들어 줄 것이다.

항상 "string"

단수로 쓴다 "Fruit" 

mongoose가 이름을 복수형 단어로 자동 변환해서 collection을 만들어준다. 

 

각 fruit의 records또는 documents들은 collection안에 저장될 것이다. 

그리곤 fruitsDB 데이터베이스 안에 들어간다. 

 

2. model 두 번째 파라미터: fruitSchema

새로 만들어진 fruits collection 이 어떤 구조물 형식을 따를지 정한다. 

have to stick to the structure that we've specified in the fruit schema. 

 

Line 12

새 fruit document 입력하기

new Fruit() <-- Line 10번에서 Fruit model을 이용해서 만들겠다. 

 

line 18

데이터 저장하기 

fruit.save(); 

한 번 저장하고 나서 커멘트 아웃한다. 안그러면 계속 저장된다. 

 

 

2. mongosh로 가서 db 만들어졌다 확인

 

2-1. db 만들어졌나 보기 

show dbs 

fruitsDB가 생긴 것을 볼 수 있다.

 

2-2  fruitsDB로 가서 

use fruitsDB 

 

2-3  collection이 만들어졌나 확인한다. 

show collections 

fruits colleciton이 만들어졌다. 

line 10에서 "Fruit"으로 입력했지만 나올 때는 다 소문자, 복수형으로 바뀌어서 나온다. 

 

 

2-4 collection 안에 데이터 입력되었나 보기 

db.fruits.find() 

 

 


 

여러 과일 한꺼번에 입력하기 

https://mongoosejs.com/docs/api.html#model_Model.insertMany

 

콘솔 

 

mongosh

 


 

 

"people" 이라는 새 collection 만들기  

이름과 나이를 넣은  person 스키마를 만들고 

이름: "John", 나이: 39 로 넣어본다.  

 

잘 저장되었나 확인하기 

 


const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost:27017/fruitsDB", { useNewUrlParser: true });

const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String
});

const Fruit = mongoose.model("Fruit", fruitSchema);

const fruit = new Fruit({
name: "Apple",
rating: 7,
review: "Pretty solid as a fruit."
});

// fruit.save();

const personSchema = new mongoose.Schema({
name: String,
age: Number
});

const Person = mongoose.model("Person", personSchema);

const person = new Person({
name: "John",
age: 39
});

// person.save();

const kiwi = new Fruit({
name: "Kiwi",
score: 10,
review: "The best fruit!"
});

const orange = new Fruit({
name: "Orange",
score: 4,
review: "Too sour for me."
});

const banana = new Fruit({
name: "Banana",
score: 3,
review: "Weird texture."
});

// Fruit.insertMany([kiwi, orange, banana], function(err) {
// if (err) {
// console.log(err);
// } else {
// console.log("Successfully saved all the fruits.")
// }
// });


Fruit.find(function(err, fruits) {
if (err) {
console.log(err);
} else {
mongoose.connection.close();

fruits.forEach(function(fruit) {
console.log(fruit.name);
});
}
});

 

 

'Databases > MongoDB | Mongoose' 카테고리의 다른 글

[Mongoose] Data Validation | 제약 걸기  (0) 2021.11.21
[Mongoose] READING | find() | close()연결끊기  (0) 2021.11.19
[MongoDB] CRUD - DELETE  (0) 2021.11.15
[MongoDB] CRUD - UPDATE  (0) 2021.11.15
[MongoDB] CRUD - QUERY (READ)  (0) 2021.11.15

댓글