Mongoose-One To One Relationship
BACKEND
NESTJS
One To One Relationship
Mongoose에서 One-to-One 관계(1:1 관계)를 구현하는 방법에는 여러 가지가 있지만, 일반적으로 두 개의 컬렉션을 만들어 ObjectId를 참조(ref)하는 방식이 가장 많이 사용된다.
1. ref를 사용한 One-to-One 관계 구현
SQL의 Relation 방식과 유사
MongoDB는 기본적으로 관계형 데이터베이스가 아니므로, 관계를 표현하려면 참조(Reference) 방식을 사용
예제: User와 Profile 간의 1:1 관계
한 명의 User는 하나의 Profile만 가짐
Profile은 User 한 명에게만 연결됨
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: String,
email: String,
profile: { type: mongoose.Schema.Types.ObjectId, ref: 'Profile' } // Profile과 1:1 관계
});
const ProfileSchema = new mongoose.Schema({
age: Number,
bio: String,
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } // User와 1:1 관계
});
const User = mongoose.model('User', UserSchema);
const Profile = mongoose.model('Profile', ProfileSchema);
populate()를 활용한 데이터 조회
async function getUserWithProfile(userId) {
const user = await User.findById(userId).populate('profile');
console.log(user);
}
2. Embed 방식 (내장 문서)
join하는 컬렉션을 프로퍼티로 할당하는 방식
위 방법 대신 Profile 데이터를 User 스키마에 직접 포함(Embed)할 수도 있음.
하지만, Profile이 자주 변경되거나 별도로 관리되어야 한다면 위 방식(Reference 방식)이 더 적절함.
const UserSchema = new mongoose.Schema({
name: String,
email: String,
profile: {
age: Number,
bio: String
}
});
const User = mongoose.model('User', UserSchema);
이 방법은 조회 속도가 빠르지만, Profile을 독립적으로 관리하기 어렵다는 단점이 있음.