Nest.js MongoDB

이건선·2023년 6월 12일
0

해결

목록 보기
44/48

MongoDB Starter

// app.module.ts

import { MongooseModule } from '@nestjs/mongoose';
import { config } from 'dotenv';

config();

...

@Module({
  imports: [MongooseModule.forRoot(process.env.MONGO_URL!), BoardsModule],
                                   
...
// boards.schema.ts

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { IsString, IsNumber, IsOptional } from 'class-validator';
import { Document } from 'mongoose';

export type StockDocument = Stock & Document;

@Schema({ timestamps: true })
export class Stock {
  @Prop({ required: true })
  @IsString()
  stockName: string;

  @Prop()
  @IsNumber()
  yesterday_value: number;

  @Prop()
  @IsNumber()
  current_value: number;

  @Prop()
  @IsNumber()
  fluctuation_rate: number;

  @Prop()
  @IsNumber()
  profit: number;
}

export const CreateStockSchema = SchemaFactory.createForClass(Stock);
// boards.model.ts

import { MongooseModule } from '@nestjs/mongoose';
import { CreateStockSchema, Stock } from '../schema/boards.schema';

export const StockSchema = MongooseModule.forFeature([
  { name: Stock.name, schema: CreateStockSchema },
]);
// boards.modules.ts

import { StockSchema } from './model/boards.model';

...

@Module({
  imports: [StockSchema],
  
...
// boards.service.ts

...

import { Model } from 'mongoose';
import { StockDocument, Stock } from './schema/boards.schema';

@Injectable()
export class BoardsService {
  constructor(
    @InjectModel(Stock.name) private stockModel: Model<StockDocument>,
  ) {}

...
profile
멋지게 기록하자

0개의 댓글