【问题标题】:typescript connection with database打字稿与数据库的连接
【发布时间】: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


【解决方案1】:

不要!!!!!! 这个东西会被翻译成普通的 JS 并且所有的服务器端信息都会被暴露(连接信息)。 尝试连接到 API。 构建一个 API 并将其 URI 公开给您的客户端应用,并根据需要执行 CRUD 操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2021-12-16
    • 2019-09-23
    • 2021-01-13
    相关资源
    最近更新 更多