What is the proper way to use the node.js postgresql module?

后端 未结 7 1824
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 01:15

I am writing a node.js app on Heroku and using the pg module. I can\'t figure out the \"right\" way to get a client object for each request that I need to query the database

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 01:16

    I am the author of pg-promise, which simplifies the use of node-postgres via promises.

    It addresses the issues about the right way of connecting to and disconnecting from the database, using the connection pool implemented by node-postgres, among other things, like automated transactions.

    An individual request in pg-promise boils down to just what's relevant to your business logic:

    db.any('SELECT * FROM users WHERE status = $1', ['active'])
        .then(data => {
            console.log('DATA:', data);
        })
        .catch(error => {
            console.log('ERROR:', error);
        });
    

    i.e. you do not need to deal with connection logic when executing queries, because you set up the connection only once, globally, like this:

    const pgp = require('pg-promise')(/*options*/);
    
    const cn = {
        host: 'localhost', // server name or IP address;
        port: 5432,
        database: 'myDatabase',
        user: 'myUser',
        password: 'myPassword'
    };
    // alternative:
    // const cn = 'postgres://username:password@host:port/database';
    
    const db = pgp(cn); // database instance;
    

    You can find many more examples in Learn by Example tutorial, or on the project's home page.

提交回复
热议问题