Pool
- Node.js course
- Advanced
- Lesson 32/83
- 5 min
Learn connection pooling with pg.Pool.
Creating a Pool
Creating a Pool: const pool = new Pool({ connectionString: "postgres://localhost/mydb" }). The connectionString carries all connection parameters in a single string.
You can also pass them separately: { host: "localhost", port: 5432, database: "test", user: "alex", password: "secret" }. The Pool opens connections lazily; the first query triggers a connection. You close all connections with pool.end(). In production setting the pool size with max is a good habit.
pool.query
pool.query(text, values) runs an SQL query. text is the SQL string, values is the parameter array. The returned object's rows field holds the result rows.
The query is asynchronous; you await it. Example: const res = await pool.query("SELECT * FROM users WHERE id = $1", [1]);. $1 is a parameter placeholder; it maps to the first item in the values array. This prevents SQL injection.
Practice Log the type of pool.query
Import the Pool class from pg. Create a pool: new Pool({}). Log typeof pool.query.
Starter code
// import the module
// create a pool
// log the type of querySample solution
const { Pool } = require("pg");
const pool = new Pool({});
console.log(typeof pool.query);Expected output
function
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the class name
const pool = new ____({ host: "localhost", database: "test" })
const pool = new Pool({ host: "localhost", database: "test" })
Explanation: new Pool({...}) creates a connection pool.
2 What does Pool provide?
- Network acceleration
- A single connection
- File compression
- A connection pool (reuse) Correct answer
Explanation: The Pool reuses connections.
3 Match each piece to its role
| Term | Meaning |
|---|---|
new Pool({...}) |
Creates a pool |
pool.query |
Runs a query |
connectionString |
Connection string |
pool.end() |
Closes the pool |