How to query another database on same host

System Information
  • Strapi Version: 4.4.3
  • Operating System: Ubuntu Server
  • Database: PostgreSQL 14
  • Node Version: v.16.17.0
  • NPM Version: 8.15.0
  • Yarn Version: -

Hi i need to query another database on the same host. I made several attempts by editing the database.js file but failed. I’m not sure if this is possible. Has anyone been able to do this before?

  • Strapi Database
    – Strapi Schema

  • Custom Database
    – Client Informations

// ./config/database.js
const path = require('path');

module.exports = ({ env }) => ({
  connection: {
    client: 'postgres',
    connection: {
      host: env('DATABASE_HOST', 'HOST'),
      port: env.int('DATABASE_PORT', 25060),
      database: env('DATABASE_NAME', strapi
      user: env('DATABASE_USERNAME', 'doadmin'),
      password: env('DATABASE_PASSWORD', 'PASS'),
      schema: env('DATABASE_SCHEMA', 'public'), // Not required
      ssl: {
        rejectUnauthorized: env.bool('DATABASE_SSL_SELF', false),
      },
    },
    debug: false
  },
  userData: { //second database
    client: 'postgres',
    connection: {
      host: env('DATABASE_HOST', 'HOST'),
      port: env.int('DATABASE_PORT', 25060),
      database: env('DATABASE_NAME', 'userData'),
      user: env('DATABASE_USERNAME', 'doadmin'),
      password: env('DATABASE_PASSWORD', 'PASS'),
      schema: env('DATABASE_SCHEMA', 'public'), // Not required
      ssl: {
        rejectUnauthorized: env.bool('DATABASE_SSL_SELF', false),
      },
    },
    debug: false,
  }
});

You could use Knex to make queries to the other db. I understand that your other DB has no connection to Strapi whatsover, so no need to define stuff in the Strapi config.

You could create a utils folder where you export a Knex instance which is configured to connect to your other DB. You could import that Knex instance from anywhere you like to make queries to that other DB.

However, depending on your use case, architecture, environment, security, scalability and so on, you might want to create another backend with a REST API around that other DB.

1 Like