【发布时间】:2018-09-14 11:11:07
【问题描述】:
我是打字稿的新手,我想创建一个与数据库的新连接并插入我在代码中提到的数据。我正确安装了软件包,我参考了网站 typeorm.io,但我无法正确安装 typescript/tsc。 src/index.ts .
import "reflect-metadata";
import {createConnection} from "typeorm";
import {User} from "./entity/User";
createConnection({
type: "mysql",
host: "localhost",
port: 3306,
username: "root",
password: "welcome123@",
database: "test",
entities: [
User
],
synchronize: true,
logging: false
}).then(async connection => {
console.log("Inserting a new user into the database...");
const user = new User();
user.firstName = "Timber";
user.lastName = "Saw";
user.age = 25;
await connection.manager.save(user);
console.log("Saved a new user with id: " + user.id);
console.log("Loading users from the database...");
const users = await connection.manager.find(User);
console.log("Loaded users: ", users);
console.log("Here you can setup and run express/koa/any other
framework.");
}).catch(error => console.log(error));
这是文件,我定义了模型。 实体/User.ts
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column()
age: number;
}
【问题讨论】:
-
代码有什么问题?
-
我无法连接数据库,这段代码是否正确?!!
-
你有错误信息吗?
-
我应该如何运行这个文件,tsc index.ts or node index.js
-
ram@thinkpad-t420:~/Desktop/task/ts/src$ node index.js /home/ram/node_modules/typeorm/decorator/columns/Column.js:44 抛出新的 ColumnTypeUndefinedError_1。 ColumnTypeUndefinedError(object, propertyName); ^ ColumnTypeUndefinedError: User#firstName 的列类型未定义且无法猜测。确保您在 tsconfig.json 中打开了 "emitDecoratorMetadata": true 选项。还要确保您已在应用程序的主条目文件顶部导入“reflect-metadata”(在导入任何实体之前)
标签: typescript connection package tsc typeorm