본문 바로가기
개발 프레임워크/NestJS

[NestJS] MongoDB 컬렉션에 문서(객체)를 삽입하기

by minhyeok.lee 2023. 2. 21.
반응형

[NestJS] MongoDB 컬렉션에 문서를 삽입하기 (하나, 여러개)

MongoDB(mongosh)에서 컬렉션에 문서를 삽입하는 3가지 방법을 mongoose를 사용하여 NestJS에서 사용하기

 - db.collection.insert(): 하나 혹은 여러개의 문서를 삽입한다.

 - db.collection.insertOne(): 하나의 문서를 삽입한다.

 - db.collection.insertMany(): 여러개의 문서를 삽입한다.

 

1. 하나의 객체(문서) 생성(db.collection.insertOne())

async createOne(createUserDto: CreateUserDto): Promise<User> {
    const createUser = new this.model(createUserDto);
    return createUser.save();
}

 - db.collection.insertOne()과 같은 기능을 사용하고자 하면 mongoose의 Model.prototype.save()를 사용하면 된다.

 - mongosh의 db.collection.insertOne()과 유사하게 동작한다.

 - 하나의 User에 대한 문서를 NestJS에서 MongoDB에 삽입할 수 있다.

 - 일반적으로 하나의 객체를 Create(POST)하는 경우 사용한다.

 

2. 여러개의 객체(문서) 생성(db.collection.insertMany())

async createMany(createUserDto: CreateUserDto[]): Promise<User[]> {
    const createUsers = this.model.insertMany(userList);
    return createUsers;
}

 - db.collection.insertMany()과 같은 기능을 사용하고자 하면 mongoose의 Model.insertMany()를 사용하면 된다.

 - mongosh의 db.collection.insertMany()과 유사하게 동작한다.

 - 여러개의 User에 대한 문서배열을 NestJS에서 MongoDB에 삽입할 수 있다.

 - 일반적으로 여러개의 객체를 Create(POST)하는 경우 사용한다.

 

 

3. db.collection.insert()의 경우

async create(
  createUserDto: CreateUserDto | CreateUserDto[],
): Promise<User | User[]> {
  return await this.model.create(createUserDto);
}

 - db.collection.insert()과 같은 기능을 사용하고자 하면 mongoose의 Model.create를 사용하면 된다.

 - mongosh의 db.collection.insert()와 유사하게 동작한다.

 - db.collection.insert()의 경우 인수로 하나의 객체 혹은 객체배열을 받아 두 개의 타입 모두 MongoDB에 생성가능하다.

 - mongosh에서도 db.collection.insert()를 사용하는 것은 인수의 타입도 두 개, 반환값의 타입도 두 개이므로 (객체 타입, 객체 배열타입) 사용을 지양한다.

  * 하나만 생성할 때는 예제1처럼 db.collection.insertOne()을 사용하는 것이 직관적이다.

  * 여러개를 생성할 때는 예제2처럼 db.collection.insertMany()를 사용하는 것이 직관적이다.

 

 - 일반적인 경우 하나의 객체를 생성할 경우와 여러개의 객체를 생성할 때는 로직이 다르기때문에 함수도 분리해주는 것이 좋고 직관적이다.

 

- db.collection.insert()는 더 이상 사용하지 않는 Mongosh방법이다

https://www.mongodb.com/docs/mongodb-shell/reference/compatibility/#std-label-compatibility

 

Compatibility Changes with Legacy mongo Shell — MongoDB Shell

Docs Home → MongoDB Shell This page describes differences between mongosh and the legacy mongo shell. In addition to the alternatives listed here, you can use the mongocompat snippet to access to legacy mongo shell APIs. Snippets are an experimental feat

www.mongodb.com

 

반응형

댓글