티스토리 뷰

728x90
반응형

[ 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);

 


[ 참고 ]

728x90
반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함