node.js开发:mysql2+typeorm --- 踩坑之路(三)

人真的有惰性思维哎

一旦懒惰了两天(周六、周日),都忘了自己想干什么了

所以说上班真是让人快乐的存在呐

----------------------------------------------------------------

过程:

目录结构:


其中,entity存放实体,dao存放对表的处理,index.ts连接数据库

数据库使用的是mysql

功能:创建user表,并且往user表中添加数据

1、安装依赖

npm install typeorm --save
npm install reflect-metadata --save
npm install mysql2

2、连接数据库(index.ts)

扫描二维码关注公众号,回复: 15875630 查看本文章
import { createConnection } from 'typeorm'
import * as dao from './dao/index'

// const Typeorm = require('typeorm')

export const dbInit = async (app) => {
    createConnection({
        type: 'mysql', // 数据库类型
        host: '127.0.0.1', // 数据库地址
        port: 3306, // 数据库端口号
        username: 'root', // 数据库用户名
        password: 'root', // 密码
        database: 'node', // 数据库名
        entities: [ __dirname + '/entity/*.ts', 'dist/data/entity/*.js'], // 引入实体
        synchronize: true,
    }).then((conn: any) => {
        console.log('数据库连接成功')
        app.listen(3000)
        dao.UserDao.addUser() // 调用方法-添加用户
        console.log('应用启动成功')
        return true
    }).catch((error: any) => {
        console.log('应用启动失败')
        console.log(error)
        return false
    })
}

3、调用连接数据库(app.ts)

import * as Koa from 'koa' // 用了koa框架
import { dbInit } from './data'

const app = new Koa()

dbInit(app)

重启项目后,控制台会输出“数据库连接成功”和“应用启动成功”

4、创建user实体类(entity/user.ts)

import {Entity, Column, PrimaryGeneratedColumn} from 'typeorm'

@Entity()
export default class User {
    @PrimaryGeneratedColumn() // 主键自增
     id: number = 1;

    @Column()
     username: string = '';

    @Column()
    password: string = '';
}

重启项目后,观察数据库,会生成user表

5、往数据库添加数据(dao/user.ts)

import {getManager} from "typeorm"
import User from '../entity/User'

export const UserDao = {
    addUser: async () => {
        const entityManager = getManager()
        let user = new User()
        user.username = 'admin'
        user.password = 'admin'
        return await entityManager.save(User, user) // user表中插入数据
    },
    updateUser: async () => {
        const entityManager = getManager()
        return await entityManager.update(User, {username: 'admin'}, {password: 'admin'}) // user表中更新数据
    },
    delUser: async () => {
        const entityManager = getManager()
        return await entityManager.delete(User, {username: 'admin'}) // user表中删除数据
    },
    findUser: async () => {
        const entityManager = getManager()
        return  await entityManager.find(User, {username: 'admin'}) // user表中查找数据
    }
}

观察步骤2,连接数据库成功后调用了添加用户的方法。

dao.UserDao.addUser() // 调用方法-添加用户

踩坑:

1、typescript不支持import和export,导致报错

app.ts: A namespace-style import cannot be called or constructed, and will cause a failure at runtime. (7038)
app.ts (4,13): Cannot use 'new' with an expression whose type lacks a call or construct signature. (2351)

观察tsconfig.json

 "esModuleInterop": true // 实现CommonJS和ES模块之间的互操作性

将它注释掉或者置为false

2、变量没有赋初始值,导致报错

User.ts(6,13): error TS2564: Property 'id' has no initializer and is not definitely assigned in the constructor.
User.ts(9,13): error TS2564: Property 'username' has no initializer and is not definitely assigned in the constructor.
User.ts(12,13): error TS2564: Property 'password' has no initializer and is not definitely assigned in the constructor.

解决:


----------------------------------------------------------------

感觉自己一直在照猫画虎

好像没啥建设性的东西

怕是最近有点浮躁呐~

关于typeorm中封装了许多处理数据库的方法

有时间的话理应整理一下

猜你喜欢

转载自blog.csdn.net/qq_31808899/article/details/80569517