在我的 Node 應用程式中,我正在運行一個腳本來生成一個使用 KnexJs 查詢構建器和 PostgreSQL 的資料庫
- “節點”:“~14.17.6”
- "knex": "^0.95.15"
- "pg": "^8.7.1"
我得到的錯誤
Cannot read property 'destroy' of undefined
TypeError: Cannot read property 'destroy' of undefined
at process.value (/app/node_modules/knex/lib/knex-builder/make-knex.js:91:26)
at process.emit (events.js:315:20)
at process.exit (internal/process/per_thread.js:169:15)
at success (/app/node_modules/knex/bin/utils/cli-config-utils.js:76:11)
at Command.<anonymous> (/app/node_modules/knex/bin/cli.js:236:9)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
我正在運行的腳本如下
const conn = {
host: process.env.POSTGRES_HOST,
database: process.env.POSTGRES_USER,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
port: process.env.POSTGRES_PORT,
charset: 'utf8',
};
const databaseName = process.env.POSTGRES_DB;
const knex = require('knex')({ client: 'pg', connection: conn });
knex
.raw('CREATE DATABASE ??', databaseName)
.then(() => console.info('Successfully created db: ' databaseName))
.catch((err) =>
console.warn('Warning: Unable to create db. Probably already exists.', err)
)
.finally(() => knex.destroy())
.then(() => {
const connection2 = knex({
client: 'pg',
connection: { ...conn, database: databaseName },
});
return connection2
.raw('CREATE EXTENSION IF NOT EXISTS citext')
.then(() => console.info('Successfully created extension citext'))
.catch((err) => console.error('Unable to create extension citext.', err))
.finally(() => connection2.destroy());
})
.then(() => process.exit(0));
我無法理解導致問題的原因以及原因
uj5u.com熱心網友回復:
我認為這個問題可能是由于對什么是 knex 實體和什么是連接實體的誤解。
在這部分:
const knex = require('knex')({ client: 'pg', connection: conn });
您使用 knex 模塊定義了連接。因此,當您呼叫“knex”在下面創建第二個連接時:
.then(() => {
const connection2 = knex({
client: 'pg',
connection: { ...conn, database: databaseName },
});
connection2不是連接,因為knex在此背景關系中是所需的連接。您可以使用以前的knex連接物件。
為了避免這些問題,我建議您將事物分開并重命名變數以使其更易于解釋:
const knex = require('knex') // this is the knex module
const connection = knex({ client: 'pg', connection: conn }) // This is a connection using knex
// So you should use `connection` instead `knex`, as you are using the connection instance to perform queries
connection
.raw('CREATE DATABASE ??', databaseName)
// ...
.then(() => {
// Now this should work and return a connection
const connection2 = knex({
client: 'pg',
connection: { ...conn, database: databaseName },
});
// But as connection2 is actually the same of connection, it could be
// const connection2 = connection;
return connection2 // or return connection
.raw('CREATE EXTENSION IF NOT EXISTS citext')
.then(() => console.info('Successfully created extension citext'))
.catch((err) => console.error('Unable to create extension citext.', err))
.finally(() => connection2.destroy());
})
另一點要談的是,如果真的有必要結束連接并在第一次destroy()呼叫后創建另一個連接。由于您可以擁有 的實體connection,因此您可以在執行查詢時使用它,如果不再需要,只需將其銷毀一次。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/403726.html
標籤:
上一篇:substring帶條件的字串
