Nestjs中使用Mongoose操作Mongodb数据库

Nestjs中操作Mongodb数据库可以使用Nodejs封装的DB库,也可以使用Mongoose。下面我们主要给大家讲讲在Nestjs中使用Mongoose操作mongodb数据库

一、安装nestjs/mongoose 以及mongoose模块

Nest 操作Mongodb官方文档:https://docs.nestjs.com/techniques/mongodb

npm install --save @nestjs/mongoose mongoose
npm install --save-dev @types/mongoose

二、配置数据库连接地址

在app.module.ts中配置数据库连接

  import { Module } from '@nestjs/common';
  import { MongooseModule } from '@nestjs/mongoose';
  
  @Module({
    imports: [MongooseModule.forRoot('mongodb://localhost/koa',{ useNewUrlParser: true })]
  })
  export class ApplicationModule {}

三、配置Schema

import * as mongoose from 'mongoose';
export const ArticleSchema = new mongoose.Schema({
  title: String,
  keywords:String,
  author: Number,
  status: String,
});

四、在控制器对应的Module中配置Model

  import { Module } from '@nestjs/common';
  import { NewsController } from './news.controller';
  import { NewsService } from './news.service';
  
  import { ArticleSchema } from './schemas/article.schema';
  import { MongooseModule } from '@nestjs/mongoose';
  
  @Module({
    imports: [MongooseModule.forFeature([{ name: 'Article', schema: ArticleSchema,collection:"article" }])],
    controllers: [NewsController],
    providers: [NewsService]
  })
  export class NewsModule {}

五、在服务里面使用InjectModel 获取数据库Model实现操作数据库

  import { Injectable } from '@nestjs/common';

  import { InjectModel } from '@nestjs/mongoose';
  
  @Injectable()
  export class NewsService {
  
      constructor(@InjectModel('Article') private readonly articleModel) {}
      
      async findAll(){
          return await this.articleModel.find().exec();
      }
  }