[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
'개발 프레임워크 > NestJS' 카테고리의 다른 글
[NestJS] 배열 구문 분석 및 유효성 검사, DTO 검증 (0) | 2023.02.23 |
---|---|
[NestJS] 매핑유형(Partial, Pick, Omit, Intersection) Type() (0) | 2023.02.23 |
[NestJS] 데이터 추출(페이지네이션), skip(), hasNext(), next() (0) | 2023.02.20 |
[NestJS] 개발환경 구성 (0) | 2023.02.20 |
[NestJS] Swagger 문서 모듈 별로 분리 (0) | 2023.02.14 |
댓글