본문 바로가기
Back Side/DBMS > MongoDB

[MongoDB] mongoose의 populate을 이용해서 편하게 다른 컬렉션 정보 가져오기

by developerBeluga 2023. 12. 8.
728x90
반응형

 

 

 

 

 

지금 누가 join하고 웃었는가?

join은 관계형 데이터베이스에서 많이 쓰인다.

SQL에서 join을 사용하면 두 테이블 간의 관계를 기반으로 데이터를 결합하여 결과를 반환한다.

 

 

 

 

그럼 MongoDB는?

$lookupd이라는 Aggregation 연산자가 있긴하다.

 

db.users.aggregate([
  {
    $lookup: {
      from: "orders",       // 결합할 다른 컬렉션
      localField: "_id",    // 현재 컬렉션의 필드
      foreignField: "userId", // 다른 컬렉션의 필드
      as: "userOrders"      // 결과를 저장할 필드 이름
    }
  }
]);

 

직접적이고 유연한 방법을 제공하지만 복잡한 쿼리를 작성해야 한다.

이때 mongoose의 populate를 쓰면 좋다.

 

 

https://mongoosejs.com/docs/populate.html

mongoose 공식문서에 말하는 populate를 요약하면 mongodb $lookup ㅇㅇ 있음 근데 populate을 사용하면 더 좋아 라고 말하고 있다.

정말 좋을까 하고 알아보도록 하자.

 

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

const UserSchema = new Schema({
  name: String,
  ...
});
const OrderSchema = new Schema({
  userId: { type: Schema.Types.ObjectId, ref: 'User' },
  product: String,
  ...
});

const User = mongoose.model('User', UserSchema);
const Order = mongoose.model('Order', OrderSchema);

// 특정 주문의 사용자 정보를 가져올 때
Order.findById(orderId).populate('userId').exec((err, userWithOrders) => {
  if (err) throw err;
  console.log(userWithOrders);
});

주문 스킴에서 userId를 넣었다.

여기에서 ref를 걸어주면 주문 조회를 할 때 populate을 이용해서 유저 스킴에 저장되어져 있는 유저 정보를 같이 가져온다.

이중으로 조회할 필요가 없다!

 

populate가 좀 더 직관적이고 사용하기 편해서 mongoose를 쓰는걸 추천한다 👍

 

 

 

 

 

 

 

 

 

 

fin.

728x90
반응형

댓글