Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在第一次使用Node和pg创建数据库后创建表_Node.js_Postgresql_Pg - Fatal编程技术网

Node.js 如何在第一次使用Node和pg创建数据库后创建表

Node.js 如何在第一次使用Node和pg创建数据库后创建表,node.js,postgresql,pg,Node.js,Postgresql,Pg,我正在尝试创建一个节点应用程序,它可以通过创建一个数据库,然后创建表和之后的字段,在数据库端进行自我设置。下面是我用来独立完成每项任务的两个函数。我能得到一些关于如何将这些结合在一起的帮助吗?我应该使用pg promise而不是pg吗 function createDatabase(){ const pool = new pg.Pool({ user: 'postgres', host: '127.0.0.1', database: 'postgres', pa

我正在尝试创建一个节点应用程序,它可以通过创建一个数据库,然后创建表和之后的字段,在数据库端进行自我设置。下面是我用来独立完成每项任务的两个函数。我能得到一些关于如何将这些结合在一起的帮助吗?我应该使用pg promise而不是pg吗

function createDatabase(){

const pool = new pg.Pool({
    user: 'postgres',
    host: '127.0.0.1',
    database: 'postgres',
    password: 'postgres',
    port: '5432'}
);

pool.query("CREATE DATABASE myApp;", 
    (err, res) => {
    console.log(err, res);
    pool.end();

});
}


function createTable(){

const pool = new pg.Pool({
    user: 'postgres',
    host: '127.0.0.1',
    database: 'myApp',
    password: 'postgres',
    port: '5432'}
);

pool.query("CREATE TABLE session(sessionguid UUID NOT NULL, created 
text NOT NULL, sessionlife integer NOT NULL)", 
    (err, res) => {
    console.log(err, res);
    pool.end();
});

}

也许下面的代码可以帮助您。现在,在“createdatabase”查询完成后,将立即在回调中创建该表

function createDatabase(){
const pool = new pg.Pool({
    user: 'postgres',
    host: '127.0.0.1',
    database: 'postgres',
    password: 'postgres',
    port: '5432'}
);

pool.query("CREATE DATABASE myApp;", (err, res) => {
    console.log(err, res);

    pool.query("CREATE TABLE session(sessionguid UUID NOT NULL, created text NOT NULL, sessionlife integer NOT NULL)", (err, res) => {
        console.log(err, res);
        pool.end();
    });
});
}

为了从代码中创建数据库,我使用客户机而不是池。下面是一个例子:

        const { Pool, Client } = require('pg')
        const client = new Client({
            user: 'postgres',
            host: 'localhost',
            password: 'postgres',
            port: 5432
        })
        await client.connect()
        await client.query(`DROP DATABASE IF EXISTS ${dbname};`)
        await client.query(`CREATE DATABASE ${dbname};`)
        await client.end()

        //call the pool you just created after the database has been created.

差不多了,但这就引出了我的下一个挑战,以及为什么我没有尝试你的解决方案。连接中的数据库是postgres,因此当启动create table时,它是在postgres数据库中创建的,而不是在它前面的行中创建的新数据库。这是否回答了您的问题?