[英]TypeORM PostgreSQL can't connect
我無法讓我的數據庫和服務器相互連接。 服務器是 express 的,數據庫是用 postgress 的 docker 鏡像創建的。
我試過了
錯誤
[2021-11-01T00:48:05.774Z] INFO: Express server started on port: 3000
DriverPackageNotInstalledError: Postgres package has not been found installed. Try to install it: npm install pg --save
at DriverPackageNotInstalledError.TypeORMError [as constructor] (/Users/alexskotner/Documents/GitHub/Aware/BackEnd/src/error/TypeORMError.ts:7:9)
at new DriverPackageNotInstalledError (/Users/alexskotner/Documents/GitHub/Aware/BackEnd/src/error/DriverPackageNotInstalledError.ts:8:9)
at PostgresDriver.loadDependencies (/Users/alexskotner/Documents/GitHub/Aware/BackEnd/src/driver/postgres/PostgresDriver.ts:1118:19)
at new PostgresDriver (/Users/alexskotner/Documents/GitHub/Aware/BackEnd/src/driver/postgres/PostgresDriver.ts:284:14)
at DriverFactory.create (/Users/alexskotner/Documents/GitHub/Aware/BackEnd/src/driver/DriverFactory.ts:36:24)
at new Connection (/Users/alexskotner/Documents/GitHub/Aware/BackEnd/src/connection/Connection.ts:122:43)
at ConnectionManager.create (/Users/alexskotner/Documents/GitHub/Aware/BackEnd/src/connection/ConnectionManager.ts:61:28)
at /Users/alexskotner/Documents/GitHub/Aware/BackEnd/src/globals.ts:77:35
at step (/Users/alexskotner/Documents/GitHub/Aware/BackEnd/node_modules/typeorm/node_modules/tslib/tslib.js:143:27)
at Object.next (/Users/alexskotner/Documents/GitHub/Aware/BackEnd/node_modules/typeorm/node_modules/tslib/tslib.js:124:57)
包.json
"pg": "^8.7.1"
類類 DatabaseAPI {
private opt: ConnectionOptions = {
type: 'postgres',
host: "localhost",
port: 5432,
username: "me",
password: "password",
database: "alex",
entities: [
User
],
synchronize: true,
logging: false
}
constructor() {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
createConnection(this.opt).then((connection: Connection) => {
// here you can start to work with your entities
const c = new Company('Aware', '0001', '')
return connection.manager
.save(c)
.then(c => {
console.log("cimpany has been saved. comp name is", c.name);
});
}).catch(error => console.log(error));
}
}
碼頭工人撰寫
version: '3.1'
services:
db:
image: postgres:14.0
container_name: postfres
volumes:
- db-data:/var/lib/postgresql/data
ports:
- 5432:5432
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
PGDATA: /var/lib/postgresql/data/
adminer:
image: adminer
ports:
- 8080:8080
volumes:
db-data:
在 docker-compose 中連接 2 個元素時,您不提供“localhost”作為主機,您需要提供服務的名稱以創建成功的連接。 因此,在這種情況下,將服務器連接到數據庫的正確方法是將服務名稱指定為 ConnectionOptions 中的主機:
private opt: ConnectionOptions = {
type: 'postgres',
host: "db",
port: 5432,
username: "me",
password: "password",
database: "alex",
entities: [
User
],
synchronize: true,
logging: false
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.