How to Add Knex to ExpressJS Apps and Connect to a Postgres Database

How to Add Knex to ExpressJS Apps and Connect to a Postgres Database

Express is one of the most popular JavaScript frameworks for building backend APIs and Postgres is a really popular relational database. How do we connect them?

Express is one of the most popular JavaScript frameworks for building backend APIs and Postgres is a really popular relational database. How do we connect the two?

If you look at the official documentation for Express, you'll see the section like this:

var pgp = require('pg-promise')(/* options */)
var db = pgp('postgres://username:[email protected]:port/database')
db.one('SELECT $1 AS value', 123)
  .then(function (data) {
    console.log('DATA:', data.value)
  })
  .catch(function (error) {
    console.log('ERROR:', error)
  })

It works for sure but it's not the way you would write it in a full fledged production application. Some of the questions that come to mind are:

  • How do you create the tables in the database?
  • How do you track changes to the database? For example, when you alter a table or create a new table. Or create/drop an index on a field. How to keep track of all these changes in your git/cvs/svn repository?
  • What if you switch from Postgres to some other database in future, say MariaDB for example? Do all your queries still work?

There might be a lot more questions but to me, the most important one feels like keeping track of changes to database in your application codebase.

node express

What is Geek Coin

What is GeekCash, Geek Token

Best Visual Studio Code Themes of 2021

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Node.js Express Tutorial | What Is Node.js Express

Express is a flexible Node.js web application framework which provides a wide set of features to develop both web and mobile applications. We dive into the features of this framework and also create a basic web application using Express.

[Hindi] Express.js Tutorial: Build RESTful APIs with Node and Express - Part 1

Express.js Tutorial: Building RESTful APIs with Node Express. nodejs tutorial with api building with get and post methods.

Node.js Express MongoDB Tutorial

Node.js Express MongoDB Tutorial is CRUD example, I have created to showcase Express web framework, MongoDB NoSQL database, and Node.js server platform.

Hire Top Node JS Developers | Best Node.js Development Company India

Hire dedicated Node JS developers & programmers in India for custom full-stack NodeJS web development projects on hourly/full-time basis. Strict NDA, 16+ years exp & 2500+ clients|450+ Experts

Node.js Crash Course Tutorial #11 - Express Router & MVC

Hey gang, in this node.js tutorial we'll take a look at the express router in order to split up our routes into separate files (keeps the code more modular &