天天看點

nest架構連接配接mongodb資料庫

作為後端語言開發自然要連接配接資料庫,對資料的增删改查,目前

nest

提供可以連接配接的資料庫有

mySQL

mongoDB

,官網位址,本文介紹使用

nest

連接配接

mongoDB

資料庫,官網介紹也很簡單,官網提供的案例

一、使用步驟

  • 1、安裝依賴包
    npm install --save @nestjs/mongoose mongoose
               
  • 2、在項目中建立一個

    database

    作為資料庫連接配接的檔案/或者叫包
    • database.providers.ts

      類似

      angular

      中使用工廠的方式把資料庫連接配接池注入到項目中
      import * as mongoose from 'mongoose';
      
      export const databaseProviders = [
        {
          provide: 'DbConnectionToken',
          useFactory: async (): Promise<mongoose.Connection> =>
            await mongoose.connect('mongodb://localhost/nest'),
        },
      ];
                 
    • database.module.ts

      就是一個導入連接配接池與導出的

      module

      檔案
      import { Module } from '@nestjs/common';
      import { databaseProviders } from './database.providers';
      
      @Module({
        components: [...databaseProviders],
        exports: [...databaseProviders],
      })
      export class DatabaseModule {}
                 
  • 3、根據官網的建立一個

    cats

    的檔案夾存放關于

    cat

    的全部資訊
  • 4、根據上文中介紹的要建立幾個基礎檔案然後注入到

    cats.module.ts

    中,再将

    cats.module.ts

    注入到

    app.module.ts

  • 5、在檔案夾下建立一個新的檔案夾和檔案(俗稱

    App

    )
    • dto

      檔案夾
    • interfaces

      檔案夾
    • schemas

      檔案夾,建立本

      App

      schema

    • cats.providers.ts

      database

      中的

      database.providers.ts

      與本檔案夾下的

      schema

      相關聯(使用

      useFactory

      依賴注入的方式)
  • 6、

    schemas

    的書寫(資料模組化)
    import * as mongoose from 'mongoose';
    
    export const CatSchema = new mongoose.Schema({
      name: String,
      age: Number,
      breed: String,
    });
               
  • 7、

    interfaces

    的書寫(接口限制資料類型)
    import { Document } from 'mongoose';
    
    export interface Cat extends Document {
      readonly name: string;
      readonly age: number;
      readonly breed: string;
    }
               
  • 8、

    dto

    的書寫(也是限制資料類型的)
    export class CreateCatDto {
      readonly name: string;
      readonly age: number;
      readonly breed: string;
    }
               
  • 9、

    cats.providers.ts

    的書寫(關鍵點)
    import { Connection } from 'mongoose';
    // 引入schema
    import { CatSchema } from './schemas/cat.schema';
    
    export const catsProviders = [
      {
        // 自己定義一個到時候在service.ts中注入
        provide: 'CatModelToken', 
        // 使用CatSchema
        useFactory: (connection: Connection) => connection.model('Cat', CatSchema),
        // DbConnectionToken是database.providers.ts裡面的key
        inject: ['DbConnectionToken'],
      },
    ];
               
  • 10、關于

    cats.service.ts

    的書寫
    import { Model } from 'mongoose';
    import { Component, Inject } from '@nestjs/common';
    import { Cat } from './interfaces/cat.interface';
    import { CreateCatDto } from './dto/create-cat.dto';
    
    @Component()
    export class CatsService {
      // 注入的CatModelToken要與cats.providers.ts裡面的key一緻就可以
      constructor(@Inject('CatModelToken') private readonly catModel: Model<Cat>) {}
    
      // 建立資料
      async create(createCatDto: CreateCatDto): Promise<Cat> {
        const createdCat = new this.catModel(createCatDto);
        return await createdCat.save();
      }
    
      // 查詢全部資料
      async findAll(): Promise<Cat[]> {
        return await this.catModel.find().exec();
      }
    
      // 根據id查詢
      async findById(_id): Promise<Cat> {
        return await this.catModel.findById(_id).exec()
      }
    }
               
  • 11、參考代碼(元件

    cats

    food

    )

二、簡單的寫法(不寫限制資料類型)

  • 1、建立一個

    book.providers.ts

    schema

    檔案夾
  • 2、參考代碼(元件

    book

    )

三、代碼下載下傳