Typeorm快速入门学习
简单粗暴,主要和mongoose差不多的使用功能,快速学习
官方githubAPI(点击跳转) 官方API(点击跳转)
1.安装(和官方一样使用mysql,其它数据库请安装其它的依赖包)
npm install typeorm reflect-metadata @types/node mysql --save
2.TypeScript编译器版本3.3或更高版本,并且您已启用以下设置tsconfig.json
“ emitDecoratorMetadata ”: true,
“ experimentalDecorators ”: true,
3.连接到mysql数据库(单个数据库连接)
import {createConnection} from "typeorm";
try{
const connection = await createConnection({
type: "mysql", // 数据库类型
host: "localhost", // host,本地localhost/127.0.0.1
port: 3306, // 数据库端口号,mysql默认3306
username: "test", // 登录数据库的账号
password: "test", // 登录数据库的密码
database: "test", // mysql中的test数据库
entities: [__dirname + "/entity/*{.js,.ts}"], //表示扫描到的实例类的位置,src下面的/entity文件夹下面的任意.ts或.js文件
synchronize: true // 是否同步
});
}catch(error){//连接出错
console.log(error);
}
3.1在项目根目录(和package.json同级的地方)创建ormconfig.json。抽离出上面的连接对象放到该文件中
{
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "test",
"password": "test",
"database": "test",
"entities": ["src/entity/*{.js,.ts}"],
"synchronize": true
}
然后连接就不需要传递对象了,typeORM会在根目录下查找ormconfig.json文件,并连接
import {createConnection} from "typeorm";
try{
const connection = await createConnection();
}catch(error){//连接出错
console.