How to Connect Strapi to PostgreSQL

It is often confusing how to connect a Strapi instance to a Postgres database, but in this article I will demystify it with examples and images.


This is a companion discussion topic for the original entry at https://strapi.io/blog/postgre-sql-and-strapi-setup
1 Like

Fantastic article by Chidume Nnamdi :clap: :clap: :clap:

We are just getting started with Strapi but we were disappointed to see that MongoDB will be dropped in V4 which is a shame as 99% of our projects use Mongo but we decided to focus on Postgres/Strapi instead and this article was very useful - thanks again.

Would be even better if this article also included deployment and managing data in production too as by sounds of it this can be a bit tricky at first.

Thanks!

Quick question: In this article, we break down the structure in the database.js file, but we pretty much skip over what the bookshelf value of the connection actually means. We see:

“In this default connection, we set the connector to the bookshelf.”

Could you please elaborate on the connection object, but in particular, what setting it to “bookshelf” actually does. Is that an arbitrary name? Who (or what) uses that name? Can we change it at will?

Is it a database name, or a schema name, or a table name, or a row name, or… what?

Maybe I’ve got a “forest and tree” understanding problem – Is it some basic fundamental entity that’s crucial to Strapi, and so implicit (as in “it’s the default, and you always configure it that way”) that I haven’t really even thought about it?

Maybe it’s specified in an ORM (or data model) somewhere? Kinda like Django-style?

@dpcunningham There are only 2 options at the moment: “Bookshelf” and “mongoose”.

Bookshelf is the JS framework used to connect to relational database systems (in the case of strapi that would be: sqlite, postgres, MySQL (and most likely MariaDB)). You can read more about it here:
https://bookshelfjs.org/

Mongo, on the other hand, is a nosql database and needs a different approach, for which there is mongoose: https://mongoosejs.com/

Depending on which DB you decide to use, you will work with either bookshelf or mongoose, when extending yours models, services etc.

In the strapi docu there are places where sample code for both of those frameworks are side-by-side (more or less, they are “tapped”), e.g. here:

Hope that helps!

Please kindly discuss how the backend (Strapi / Postgres) can be deployed.

I haven’t tried it myself yet (and leave this comment as a kind of reminder to myself), but maybe the manual setup creates the PostrGes configuration anyway, when entering the proper info.

A video that details the pg setup for a strapi 3 install can be found here: Getting started with Strapi Headless CMS on mac with PostgreSQL [ strapi tutorial ] - YouTube

So I assume the steps to go would be:

  • setup pg
  • setup strapi4 manually (that is: NOT quickstart)