Schema.Types.ObjectId
는 MongoDB의 ObjectId 타입을 나타낸다. ObjectId는 MongoDB에서 문서를 식별하기 위해 사용되는 12바이트의 고유한 식별자이다.
ref
랑 한쌍으로 쓰이는 것 같다. 어떤 모델의 ObjectId를 사용할 것인지를 써주면 되는 것 같다.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: String,
email: String,
posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
});
const postSchema = new Schema({
title: String,
content: String,
author: { type: Schema.Types.ObjectId, ref: 'User' }
});
const User = mongoose.model('User', userSchema);
const Post = mongoose.model('Post', postSchema);
userSchema
에서 posts
필드는 Schema.Types.ObjectId
를 사용하여 Post
모델을 참조하고 있다. 마찬가지로 postSchema
에서 author
필드는 Schema.Types.ObjectId
를 사용하여 User
모델을 참조하고 있다.
Schema.Types.ObjectId
를 사용하면 관계형 데이터베이스의 외래 키(Foreign Key)와 유사한 기능을 Mongoose에서 구현할 수 있다. 이를 통해 컬렉션 간의 관계를 정의하고 관련 문서를 쿼리하거나 조인할 수 있다.