mongoose 패키지 설치
npm install --save @nestjs/mongoose mongoose
DB만 관리하는 Module에 몽구스 모듈 추가
forRoot가 Connect라고 생각하면 됨.
imports: [
MongooseModule.forRoot(process.env.MONGODB_URL),
]
스키마 만들기
test.model.ts
import * as mongoose from "mongoose"
export const TestSchema = new mongoose.Schema(
{
testId: {
type: String,
required: true,
unique: true,
},
testPw: {
type: String,
required: true,
},
},
{ timestamps: true }
)
export interface Test extends mongoose.Document {
_id: string;
testId: string;
testPw: string;
}
사용하려는 Module에 Import 해주기
imports: [MongooseModule.forFeature([{ name: "test", schema: TestSchema }])],
인젝션 후 사용하기~
test.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Test } from './test.model';
@Injectable()
export class UsersService {
constructor(@InjectModel('test') private readonly testModel: Model<Test>) {}
async insertUser(testId: string, testPw: string) {
const testid = testId.toLowerCase();
const newUser = new this.testModel({
testId,
toLowerCase,
});
await newTest.save();
return newTest;
}
}