🔸 mongoose
mongoose의 메서드들 중에 연결된 DB의 내용을 연계해서 불러와 보여주는 'populate' 를 다루려한다.
1. populate
const post = new mongoose.Schema({
userId:{
type: mongoose.Schema.Types.ObjectId,
required: true,
ref:'user'
},
nickname:{
type: String,
required: true
},
title:{
type: String,
required: true
},
password:{
type: String,
required: true
},
content:{
type:String
}
},{versionKey:false, timestamps:{createdAt:true,updatedAt:true}});
위의 코드를 보고 눈치챌수있는 점은 포스트 별로 연계되어있는 유저, 즉 작성자가 존재한다는걸 알수있다.
먼저 post 라는 스키마가 존재하고, 각 document 마다 'user' 라는 스키마와 연결이 되어있다는 것이다.
근데 데이터를 받아서 보는 입장에서 단순 ' userID : 6490657c20cca2d9a0d3e082 ' 라고 보게되면 이 유저가 누구인지 어떤 데이터를 갖고있는지 알수가 없다. 그래서 연계되어 있는 user 라는 DB에서 해당 정보를 가져오게끔 하는게 이 populate 이다.
🔥 불러오기 이전의 데이터
{
"_id": "6491193cce9b305c5f646bb0",
"userId": "6490657c20cca2d9a0d3e082",
"nickname": "singer",
"title": "BatMan",
"password": "gnsrpdlcm123!",
"content": "Godam city guardian",
"createdAt": "2023-06-20T03:13:00.230Z",
"updatedAt": "2023-06-20T03:13:00.230Z"
}
🔥 불러오기 이후의 데이터
{
"_id": "6491193cce9b305c5f646bb0",
"userId": {
"_id": "6490657c20cca2d9a0d3e082",
"name": "chalie puth",
"nickname": "singer",
"password": "gnsrpdlcm123!"
},
"nickname": "singer",
"title": "BatMan",
"password": "gnsrpdlcm123!",
"content": "Godam city guardian",
"createdAt": "2023-06-20T03:13:00.230Z",
"updatedAt": "2023-06-20T03:13:00.230Z"
}
그럼 이 populate 메서드를 어떻게 사용해야 할까?
const datas = await Post.find().sort({"createdAt":-1}).populate('userId');
불러온 데이터들에 대해 해당 '필드'를 통해 정보를 열어달라 하면 된다.
❗️ DB 명( Ex. user )을 적으면 오류가 난다. post 스키마 내에 존재하는 필드명인 'userId' 로 적어줘야 한다.
👉 만약 불러올 user 라는 데이터 중에서 민감한 데이터나 노출시키지 않고싶은 데이터가 존재할 경우엔 지정도 가능하다.
const datas = await Post.find().sort({"createdAt":-1}).populate('userId','_id name');
이런식으로 populate('userId','_id name') 내가 받아오고 싶은 필드명만 공백을 통한 구분자로 입력을 해주면 해당 값만 가져오게된다.
'회고 > TIL' 카테고리의 다른 글
2023 - 07 - 05 TIL (0) | 2023.07.05 |
---|---|
2023 - 07 - 04 TIL (0) | 2023.07.04 |
2023-06-19 TIL (0) | 2023.06.20 |
2023-06-13 TIL (0) | 2023.06.14 |
2023-05-26 TIL (0) | 2023.05.26 |