美文网首页
NestJS 连接数据库

NestJS 连接数据库

作者: niccky | 来源:发表于2018-09-30 15:10 被阅读0次

    前置条件

    1. 安装 mongodb 服务
      文件下载地址:
    https://www.mongodb.com/download-center?jmp=nav#community
    

    方式一:

    wget https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-4.0.2.tgz
    tar -zxvf mongodb-osx-ssl-x86_64-4.0.2.tgz
    mv mongodb-osx-ssl-x86_64-4.0.2 mongodb
    mv mongodb /usr/local/mongodb
    

    配置 zshrc 文件

    vi ~/.zshrc
    export PATH=/usr/local/mongodb/bin:$PATH
    source ~/.zshrc
    

    方式二:

    brew update
    brew install mongodb
    mkdir -p /data/db
    
    启动服务 
    mongod --config /usr/local/etc/mongod.conf
    

    安装 mongo 依赖包

    yarn add mongoose @nestjs/mongoose
    yarn add @types/mongoose --dev
    

    配置数据库连接

    ...
    @Module({
      imports: [
        ShareModule,
        AdminModule,
        MongooseModule.forRoot('mongodb://localhost:27017/blog'),
      ],
     ...
    })
    export class AppModule {}
    

    添加 schema

    import * as mongoose from 'mongoose';
    export const AdminSchema = new mongoose.Schema({
      name: String,
    });
    

    添加 model

    import { Document } from 'mongoose';
    export interface AdminModel extends Document {
      name: string;
    }
    

    添加数据操作服务

    import { Injectable } from '@nestjs/common';
    import { InjectModel } from '@nestjs/mongoose';
    import { AdminModel } from '../models';
    import { Model } from 'mongoose';
    
    @Injectable()
    export class AdminService {
      constructor(
        @InjectModel('admin') private readonly adminModel: Model<AdminModel>,
      ) {}
    
      async create(dto?: AdminModel): Promise<AdminModel> {
        const admin = new this.adminModel({
          name: 'see',
        });
        return await admin.save();
      }
    
      async findAll(): Promise<AdminModel[]> {
        return await this.adminModel.find().exec();
      }
    }
    

    配置 collection

    import { Module } from '@nestjs/common';
    import { controllers } from './controller';
    import { MongooseModule } from '@nestjs/mongoose';
    import { AdminSchema } from './schemas/admin.schema';
    import { AdminService } from './services';
    
    @Module({
      imports: [
        MongooseModule.forFeature([
          { name: 'admin', schema: AdminSchema, collection: 'admin' },
        ]),
      ],
      controllers: [...controllers],
      providers: [AdminService],
    })
    export class AdminModule {}
    

    测试连接

    import { Controller, Get, Post, Body, Render, Res } from '@nestjs/common';
    import { routes } from '@config';
    import { AdminService } from '../services';
    
    const { prefix } = routes.admin;
    
    @Controller(prefix)
    export class AdminController {
      constructor(private readonly service: AdminService) {}
     
      @Get('getUserInfo')
      @Render('admin/user_list')
      async adminList() {
        const data = await this.service.findAll();
        console.log(data);
        return {
          data,
        };
      }
    }
    

    2018.9.30 深圳 天之骄子

    相关文章

      网友评论

          本文标题:NestJS 连接数据库

          本文链接:https://www.haomeiwen.com/subject/wjewoftx.html