Postgres.js
Connecting with Postgres.js
Postgres.js is a full-featured Postgres client for Node.js and Deno.
1
Install
Install Postgres.js and related dependencies.
_10npm i postgres
2
Connect
Create a db.js
file with the connection details.
To get your connection details, go to your Database Settings
. Make sure Use connection pooling
is enabled. Choose Transaction Mode
if you're on a platform with transient connections, such as a serverless function, and Session Mode
if you have a long-lived connection. Copy the URI and save it as the environment variable DATABASE_URL
.
_10// db.js_10import postgres from 'postgres'_10_10const connectionString = process.env.DATABASE_URL_10const sql = postgres(connectionString)_10_10export default sql
3
Execute commands
Use the connection to execute commands.
_11import sql from './db.js'_11_11async function getUsersOver(age) {_11 const users = await sql`_11 select name, age_11 from users_11 where age > ${ age }_11 `_11 // users = Result [{ name: "Walter", age: 80 }, { name: 'Murray', age: 68 }, ...]_11 return users_11}