Member-only story

The Easiest Way to Query Postgres in Node.js (securely)

Forbes Lindesay
3 min readSep 27, 2019

--

When you’re querying Postgres, you need to choose between:

  • Use an ORM. This givers you “native” feeling APIs to query the database.
  • Use raw SQL. This gives you the ultimate flexibility & performance, and gives you more transferable skills – it’s always helpful to know how to write SQL.

Postgres ORM 📦

If you want to use an ORM to query Postgres, I recommend using https://typeorm.io. If you’re starting with a fresh project, you can use their typeorm init CLI command:

npx typeorm init --name MyProject --database postgres
cd MyProject && yarn

You’ll then need to edit ormconfig.json to add your database connection options. You’ll need to add a file in src/entity for each table in your database.

“ORMs do not give you transferable skills”

https://typeorm.io/#undefined/quick-start has detailed instructions on how to configure this. You can then use a JavaScript API to create records in your database:

import {createConnection} from "typeorm";
import {Photo} from "./entity/Photo";
async function createPhoto() {
const connection = await createConnection({
type: 'postgres',
url:
process.env.DATABASE_URL
|| 'postgres://test:test@localhost/test'
});
const photo = new Photo();
photo.name = "Me and Bears"…

--

--

Forbes Lindesay
Forbes Lindesay

Written by Forbes Lindesay

JavaScript enthusiast and maintainer of many open source projects.

Responses (1)