【发布时间】:2020-12-25 07:28:09
【问题描述】:
我正在尝试开始使用 TypeORM,但无法让 createConnection 工作。我运行默认的tpyeorm init 服务器文件,但没有显示错误或日志记录,也没有更新 postgres 数据库。
index.ts
import "reflect-metadata";
import {createConnection, ConnectionOptions} from "typeorm";
import {User} from "./entity/User";
import * as ormconfig from '../ormconfig.json';
console.log("is the file called correctly?");
createConnection(ormconfig as ConnectionOptions).then(async connection => {//ive also tried removing this 'async' keyword, but that doesnt help
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));
console.log('is this code reached?')
ormconfig.json(注意:我把 postgres 密码改成了 'root')
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "postgres",
"password": "root",
"database": "mhfit",
"synchronize": true,
"logging": true,
"entities": [
"src/entity/**/*.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
"subscribers": [
"src/subscriber/**/*.ts"
],
"cli": {
"entitiesDir": "src/entity",
"migrationsDir": "src/migration",
"subscribersDir": "src/subscriber"
}
}
运行启动会给出以下输出:
> mhfit-server@0.0.1 start /home/james/Documents/mhfit/mhfit-server
> ts-node src/index.ts
is the file called correctly?
is this code reached?
请注意,没有其他日志记录语句被命中。这是为什么?也没有显示错误。
我本地机器上的 postgres 数据库:
User$ sudo -i -u postgres
'postgres@user:~$ psql
postgres=# \list
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
mhfit | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
(4 rows)
尝试启动服务器后未创建默认User表
postgres-# \c mhfit
You are now connected to database "mhfit" as user "postgres".
mhfit-# \dt
Did not find any relations.
Update
我跟着并从this tutorial 下载了代码,神奇地它起作用了。但不幸的是我的旧项目仍然失败......
最后我尝试弄乱我的模型,发现失败是由于 TypeORM 不喜欢我如何设置我的一些模型。我有一个模型A,它可以有两个模型数组B(B 存在于事件A 之前,B 存在于事件A 之后)。
在 TypeORM 中,我将其设置为 A 上的 2 个 OneToMany 关系,以及 B 类上的 2 个 ManyToOne 关系。不过,这会导致 TypeORM 崩溃。这样做的正确方法是什么?
答:
...
@OneToMany(type => B, preB => preB.preA)
preBs: B[];
@OneToMany(type => B, postB => postB.postA)
postEmotions: B[];
乙:
...
@ManyToOne(type => A, preA => preA.preBs)
preA: A;
@ManyToOne(type => A, postA => postA.postBs)
postA: A;
【问题讨论】:
标签: javascript node.js postgresql typeorm