安装nestjs/mongoose 以及mongoose模块
cnpm install --save @nestjs/mongoose mongoose
配置数据库连接地址
在app.module.ts中配置数据库连接
import { AppController } from './modules/app/app.controller';
import { StudentsModule } from './modules/students/students.module';
@Module({
imports:[MongooseModule.forRoot('mongodb://127.0.0.1:27017/students', {useNewUrlParser: true})]
})
export class AppModule {}
配置Schema
配置schema需要和数据库字段对应,用来操作数据库
import * as mongoose from 'mongoose';
export const StudentsSchema = new mongoose.Schema({
name: String,
age: Number,
sex: String
})
在使用的控制器对应的Module中配置Model
import { Module } from '@nestjs/common';
import { StudentsController } from './students.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { StudentsSchema } from 'src/schema/students.schema'; // 定义的schema模型
import { StudentsService } from './students.service';
@Module({
imports: [MongooseModule.forFeature([
{
name: 'Students', // 需要个schema名称对应
schema: StudentsSchema, // 引入的schema
collection: 'students' // 数据库名称
}
])],
controllers: [StudentsController],
providers: [StudentsService]
})
export class StudentsModule {}
定义服务操作数据库
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
@Injectable()
export class StudentsService {
constructor(
@InjectModel('Students') private readonly studentsModel
) {}
async studentsInfo() {
return await this.studentsModel.find().exec();
}
}
在对应的控制器中调用服务
import { Controller, Get } from '@nestjs/common';
import { StudentsService } from './students.service';
@Controller('students')
export class StudentsController {
constructor(private readonly studentsService: StudentsService) {}
@Get()
index() {
return this.studentsService.studentsInfo();
}
}