Nestjs入门学习之搭建七牛云工具系列三(MongoDB、MySQL)

476 阅读4分钟

前面两篇文章主要介绍了nestjs的一些基础性的概念以及如何使用,通过前两篇文章的学习应该对nestjs有了大概的了解了,今天我们来分享一个非常重要的知识----数据库接入

我们主要介绍两种常用数据的接入,MongoDB、MySQL,在开始学习这篇文章之前,你需要了解这个两个数据的基础以及入门使用。

MongoDB

MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似jsonbson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引

在这里我默认大家已经掌握了MongoDB的基本使用,那接下来咋们就直接进入主题!

依赖 mongoose、@nestjs/mongoose
你可能会有个疑问,不是用MongoDB吗,为啥需要安装mongoose???
答:是因为直接通过编程去操作数据库效率低,所以有mongoose这种工具来提高操作MongoDB数据的效率,我们把它叫做对象关系映射(Object Relational Mapping,简称ORM),不同的数据库有不同的ORM工具,但原理是一样的。\

ORM:对象关系映射(Object Relational Mapping,简称ORM),目的是想像操作对象一样操作数据库.因为数据库不是面向对象的,所以需要编程进行映射. mongoose文档链接 www.mongoosejs.net/docs/schema…

1. 搭建schema数据模型
import mongoose from 'mongoose';

export const UserSchema = new mongoose.Schema({
  username: {
    // 用户名
    type: String,
    required: true,
  },
  email: {
    // 邮箱
    type: String,
    required: true,
  },
  password: {
    // 密码
    type: String,
    // select: false, // 查询中不包含该字段,意思是取用户时不会返回用户密码,避免暴露出来,虽然是通过加密的
    required: true,
  },
  avatar: {
    // 头像
    type: String,
    default: null,
  },
  cover: {
    type: String, // 封面
    default: null,
  },
  channelDescription: {
    // 频道介绍
    type: String,
    default: null,
  },
  subscribersCount: {
    type: Number,
    default: 0,
  },
  createdAt: {
    // 创建时间
    type: Date,
    default: Date.now,
  },
  updatedAt: {
    // 更新时间
    type: Date,
    default: Date.now,
  },
});
2. 根目录引入MongooseModule连接数据库

app.module.ts

@Module({
  imports: [
    MongooseModule.forRoot(
      'mongodb://xxxxx',
    ),
  ],
  controllers: [],
  providers: [],
})
3. 使用模块引入MongooseModule注册schema

user.module.ts

@Module({
  imports: [
    //这里添加配置。对应引入模块(注意里面的括号结构别给坑了。这里我卡了半天)
    MongooseModule.forFeature([
      { name: 'User', schema: UserSchema, collection: 'users' },
    ]),
  ],
  controllers: [],
  providers: [],
})
4. 使用mongoose来操作数据库

constructor(@InjectModel('User') private userModel) {}

user.service.ts

@Injectable()
export class UserService {
  constructor(@InjectModel('User') private userModel) {}

  /**
   * 用户创建
   */
  async create(createUserDto: CreateUserDto) {
    createUserDto.password = md5(createUserDto.password);
    const user = this.userModel(createUserDto);
    await user.save();
    return user;
  }

  find(info) {
    return this.userModel.find(info);
  }
  findByEmail(email: string): object {
    return this.userModel.findOne({ email });
  }
  findByUsername(username: string): object {
    return this.userModel.findOne({ username });
  }

  async findAll() {
    const users = await this.userModel.find();
    return users.map((item) => {
      const element = JSON.parse(JSON.stringify(item));
      delete element.password;
      return element;
    });
  }

  async findOne(info) {
    const user = await this.userModel.findOne(info);
    return user;
  }

  async update(json1: UserInterface, json2: UserInterface) {
    return await this.userModel.updateOne(json1, json2);
  }

  async remove(info) {
    return await this.userModel.deleteOne(info);
  }
}

建议自己生成项目来练习,这样更有效果!

MySql

MySQL是一个关系型数据库管理系统 由瑞典MySQL AB 公司开发,属于 Oracle 旗下产品。MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQL是最好的 RDBMS (Relational Database Management System,关系数据库管理系统) 应用软件之一。

MySQL是一种关系型数据库管理系统,关系数据库将数据保存在不同的表中,而不是将所有数据放在一个大仓库内,这样就增加了速度并提高了灵活性。

依赖 typeorm、@nestjs/typeorm
同样的意思,也是利用mysqlorm工具来操作数据库,orm是什么就不重复介绍了
typeorm文档链接:typeorm.biunav.com/

1. 搭建数据表模型
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Photo {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  description: string;

  @Column({ default: 'hello' })
  filename: string;

  @Column({ default: 0 })
  views: number;

  @Column()
  isPublished: boolean;

  @Column()
  age: number;
}
2. 根目录引入TypeOrmModule

app.module.ts

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost', // host
      port: 3306, // 端口
      username: '数据连接用户名',
      password: '数据库连接密码',
      database: '数据名称',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
3. 使用模块引入TypeOrmModule注册entity

article.module.ts

import { TypeOrmModule } from '@nestjs/typeorm';
import { Photo } from '../entity/photo.entity';

@Module({
  imports: [TypeOrmModule.forFeature([Photo])],
  controllers: [ArticleController],
  providers: [ArticleService],
})
export class ArticleModule {}
4. 使用typeorm来操作数据库

引入@InjectRepository(Photo) private readonly photoRepository: Repository<Photo>

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Photo } from '../entity/photo.entity';
import { Repository } from 'typeorm';

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(Photo)
    private readonly photoRepository: Repository<Photo>,
  ) {}
  // 新增
  async addArticle(info) {
    const photo = await new Photo();
    Object.assign(photo, info);
    return await this.photoRepository.save(photo);
  }
  // 查找(多种不同的查找形式都在下面)
  async findAll(query) {
    return await this.photoRepository.find({ where: query });
    // return await this.photoRepository.findBy(query);
    // return await this.photoRepository.find({
    //   select: ['id', 'description'],
    // });
    // return await this.photoRepository.findOne({
    //   where: { filename: '4234234' },
    // });
    // return await this.photoRepository.findAndCountBy({ age: 0 });
    // return await this.photoRepository.findBy({ age: 0 });
    // return await this.photoRepository.findAndCount({ where: { age: 0 } });
  }
  // 更新
  async update() {
    let photoToUpdate = await this.photoRepository.findOne(1);
    photoToUpdate.name = "Me, my friends and polar bears";
    await this.photoRepository.save(photoToUpdate);
  }
  // 删除
  delete() {
    let photoToRemove = await this.photoRepository.findOne(1);
    await this.photoRepository.remove(photoToRemove);
  }
}

写在最后

按照文章写的四个步骤加以实践练习便能掌握,加油!全栈铁汁们!