node.js - “ConnectionNotFoundError:未找到连接“默认”” - 类属性
问题描述
我正在学习 NodeJS,任务是构建一个简单的消息传递服务。老师使用的是 SQLite3,但我决定使用 Postgres,因为它是我们公司项目中使用的数据库。
错误:“ConnectionNotFoundError:未找到连接“默认””
// server.ts
import 'reflect-metadata';
import express from 'express';
import { createConnection } from 'typeorm';
import router from './router';
(async () => {
const PORT = 3333;
console.log('before');
await createConnection();
console.log('after');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(router);
app.listen(PORT, () => {
console.log(`App is running on port ${PORT}`);
});
})();
我有以下MessagesService
// this works just fine
class MessagesService {
async create({ user_id, text, admin_id }: MessagesCreateInterface): Promise<Message> {
const repository = getCustomRepository(MessagesRepository);
const message = repository.create({
admin_id,
text,
user_id,
});
await repository.save(message);
return message;
}
async listByUser(user_id: string): Promise<Array<Message>> {
const repository = getCustomRepository(MessagesRepository);
const messages = await repository.find({ user_id });
return messages;
}
}
由于getCustomRepository
在两个函数中都被调用,并尝试将其转换为类属性:
class MessagesService {
repository: MessagesRepository;
constructor() {
console.log('constructor');
this.repository = getCustomRepository(MessagesRepository);
}
...
}
但后来我明白了ConnectionNotFoundError: Connection "default" was not found.
。
实验
使用
setTimeout
insideconstructor
:访问连接。Consoles.log:我得到“之前”和“构造函数”打印,但不是“之后”。
有人可以帮我理解发生了什么吗?由于我使用的是 async/await,MessageService
因此在建立连接之前不应调用。我在这里打破了一些模式吗?
解决方案
您没有将连接选项传递给 TypeORM,因此它不知道如何连接和设置连接(这是默认连接)。
不带参数调用await createConnection()
将从文件中加载连接选项,并且(据我所知)您没有任何ormconfig.X文件。
要将连接选项传递给 TypeORM,您有三个选项:
- 连接选项对象
请参阅https://typeorm.io/#/connection。调用createConnection({ ... })
时直接传递连接选项(对象) 。 例子:
const connection = await createConnection({
type: "postgres",
host: "localhost",
port: 5432,
username: "test",
password: "test",
database: "test"
});
- ormconfig.X 文件
参见https://typeorm.io/#/using-ormconfig。在项目根目录中
加载一个ormconfig.[extension]文件。
支持的 ormconfig 文件扩展名有:.json、.js、.ts、.env、.yml 和 .xml。
示例(ormconfig.json):
{
"type": "postgres",
"host": "localhost",
"port": 5432,
"username": "test",
"password": "test",
"database": "test"
}
- 环境变量
见https://typeorm.io/#/using-ormconfig/using-environment-variables。
TypeORM 自动在环境变量或项目根目录中的.env或ormconfig.env中搜索连接选项(靠近 package.json)。
例子:
TYPEORM_CONNECTION = postgres
TYPEORM_HOST = localhost
TYPEORM_PORT = 5432
TYPEORM_USERNAME = test
TYPEORM_PASSWORD = test
TYPEORM_DATABASE = test
推荐阅读
- c++ - 如何将struct的函数转换为C
- python - Django:从用户序列化程序获取用户配置文件
- reactjs - React Router 在隐身模式下无法识别身份验证令牌(AAD B2C)
- c++ - 从clang c++20模块中导出全局变量
- databricks - 在 Azure Databricks 中连接到 Azure 数据库时出现超时错误
- jquery - 在jquery中访问json值的问题
- c - 请帮助我使用 C(终端)中的菜单,因为我的教授不能
- python - joblib 并将新行添加到数据框
- palantir-foundry - 如何减少代工厂数据集中的文件数量?
- java - 检查 FirebaseUser 是否有“真实”的 ProfilePicture 集