1、安装包
数据库用的postgresql,所以要安装pg。
npm i @nestjs/typeorm typeorm pg
2、连接库
app.module.ts:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { NewsModule } from './news/news.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { CateModule } from './cate/cate.module';
@Module({
imports: [TypeOrmModule.forRoot({
"type": "postgres",
"host": "localhost",
"port": 5432,
"password": "admin",
"username": "postgres",
"database": "test",
synchronize:true,
entities: [__dirname + '/**/entities/*.entity{.ts,.js}'], // 实体文件位置
autoLoadEntities:true
}),NewsModule, CateModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
3、定义实体
news.entity.ts:
import { Column, PrimaryGeneratedColumn,Entity, CreateDateColumn } from "typeorm";
@Entity({
name: 'news'
})
export class News {
@PrimaryGeneratedColumn('uuid')
id:string
@Column()
name:string
@CreateDateColumn()
createTime: Date
}
news.module.ts:
import { Module } from '@nestjs/common';
import { NewsService } from './news.service';
import { NewsController } from './news.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { News } from './entities/news.entity';
@Module({
imports:[TypeOrmModule.forFeature([News])],
controllers: [NewsController],
providers: [NewsService],
})
export class NewsModule {}