NestJS 连接数据库

前置条件

  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,
  ) {}

  async create(dto?: AdminModel): Promise {
    const admin = new this.adminModel({
      name: 'see',
    });
    return await admin.save();
  }

  async findAll(): Promise {
    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 连接数据库)