一、安装 nestjs/mongoose 以及 mongoose 模块
npm install --save @nestjs/mongoose mongoose
npm install --save-dev @types/mongoose
二、配置数据库连接地址
// app.module.ts
import { MongooseModule } from '@nestjs/mongoose';
@Module({
MongooseModule.forRoot('mongodb://127.0.0.1:27017/koa',{ useNewUrlParser: true })
})
三、配置 Schema
// schemas/article.schema.ts
import * as mongoose from 'mongoose';
export const ArticleSchema = new mongoose.Schema({
title: String,
author: String,
keywords: String,
content: String,
status: Number
});
四、在控制器对应的 Module 中配置 Model
// article.module.ts
import { MongooseModule } from '@nestjs/mongoose';
import { ArticleSchema } from '../../schemas/article.schema';
@Module({
imports: [MongooseModule.forFeature([
{
name: "Article",
schema: ArticleSchema,
collection: 'article', // 数据库的表名称
}
])],
})
五、在服务里面使用 InjectModel 获取数据库 Model 实现 操作数据库
// article.service.ts
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
@Injectable()
export class ArticleService {
// 使用 InjectModel 获取 admin.module.ts 中的 MongooseModule 的参数
constructor(@InjectModel('Article') private readonly articleModel) { }
// 在数据库里面查询全部文字
async findAll() {
const result = await this.articleModel.find().exec()
return result;
}
}
// article.controller.ts
import { ArticleService } from './../../service/article/article.service'; // 引入服务
import { Controller, Get } from '@nestjs/common';
@Controller('admin/article')
export class ArticleController {
constructor(private articleService: ArticleService) { } // 依赖注入
@Get()
async index() {
var result = await this.articleService.findAll();
return result;
}
}
六、多个数据库
// app.module.ts
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
@Module({
imports: [
MongooseModule.forRoot('mongodb://localhost/test', {
connectionName: 'cats',
}),
MongooseModule.forRoot('mongodb://localhost/users', {
connectionName: 'users',
}),
],
})
export class AppModule { }