作為後端語言開發自然要連接配接資料庫,對資料的增删改查,目前提供可以連接配接的資料庫有
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