[NestJS+MongoDB+Mongoose] MongoDB 외래키 나타내기
[ ERD Diagram ]
TypeORM과 다르게 Mongoose 에서는 어떻게 외래키를 표현할까 궁금해서 기록하게 되었다.
특히 마켓 모델 을 구현 해야되는데, 다른 모델의 PK(Primary Key)를 참조해야되는 컬럼이 존재할 때
어떻게 코드를 작성해야될지 몰랐다. 그래서 공식다큐먼트를 읽기로했다 :)
[참고] 공식 다큐먼트들
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac
docs.nestjs.com
Mongoose v6.7.2: SchemaTypes
SchemaTypes handle definition of path defaults, validation, getters, setters, field selection defaults for queries, and other general characteristics for Mongoose document properties. You can think of a Mongoose schema as the configuration object for a Mon
mongoosejs.com
@Schema() : 스키마 정의이자, 클래스를 나타내는 데코레이터 이다.
@Prop() : 다큐먼트의 프로퍼티를 정의하는 데코레이터 이다.
(1) required : NOT NULL = 값이 반드시 필요함
@Prop({ required: true })
name :string;
(2) default : 기본값
@Prop({ default: '한국' })
country :string;
@Prop({ default: Date.now })
createdAt : Date;
(3) 외래키 나타내기
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 모델명 })
외래키명: 모델타입;
(4) 마켓모델 작성완료
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose from 'mongoose';
import {
Product,
ProductDocument,
} from '../../products/schemas/product.schema';
import { User, UserDocument } from '../../users/schemas/user.schema';
export type MarketDocument = Market &
mongoose.Document & { seller: UserDocument } & {
product: ProductDocument;
};
@Schema()
export class Market {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' }) // 외래키
seller: User; // 판매자 아이디
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Product' }) // 외래키
product: Product; // 상품 아이디
@Prop({ default: Date.now })
createdAt: Date; //등록일
@Prop({ default: null })
deletedAt: Date; //삭제일
}
export const MarketSchema = SchemaFactory.createForClass(Market);
[ 참고 ]
[nest.js] Mongoose사용해보기
introduction Mongodb를 nestjs에서 사용하는방법이 공식문서에는 두가지정도 소개하고있습니다. 저는 이 문서를 따르겠습니다 다른 문서는 여기있습니다. 이 문서는 약간 express에서 Mongoose를 다루듯이
velog.io
[Nest JS ] Mongo
Nest는 MongoDB 데이터베이스와의 통합을 위해 두가지 방법을 지원한다.MongoDB용 커넥터가 있는 내장 TypeORM 모듈을 사용하거나 MongoDB 개체 모델링 도구인 Mongoose를 사용할 수 있다. TypeORM은 아직까지
velog.io
Modelling Entity Relations In MongoDB | Alexander Paterson
The flexibility of MongoDB means more decisions must be made by the developer
alexanderpaterson.com