Syntax for second database queries

System Information
  • Strapi Version: 3.5.0-beta.0
  • Operating System: Ubuntu 20.04.1 LTS
  • Database: MongoDB
  • Node Version: v12.20.0
  • NPM Version: 6.14.8
  • Yarn Version: None

Short: What is the Strapi syntax to query my second Mongo database?

Long: Im not able to figure out how to query my second Mongo database. I have the following structure in my database.js (root/config/database.js) file:

module.exports = ({ env }) => ({
  defaultConnection: 'default',
  connections: {
    default: {
      connector: 'mongoose',
      settings: {
        uri: process.env.DATABASE_URI
      },
      options: {
        // authenticationDatabase: env('AUTHENTICATION_DATABASE', null),
        ssl: env.bool('DATABASE_SSL', true),
      },
    },
    courses: {
      connector: 'mongoose',
      settings: {
        uri: process.env.DATABASE_URI_COURSES
      },
      options: {
        // authenticationDatabase: env('AUTHENTICATION_DATABASE', null),
        ssl: env.bool('DATABASE_SSL', true),
      },
    }
  },
});

To query the default database I just use the strapi.query(). But I cant figure out how I write for example: strapi.query(‘cities’).findOne({ cityId: cityId }); for my courses database. Not able to find this in the documentation nor on Stackoverflow.

How do I accomplish this?

Here’s what I would do (seem to be working for me) :

  1. Create a collection called city, add the fields you need, Strapi will then generate the files needed in the api folder.
  2. navigate to api/city/models/city.settings.json, and add at the top of the code
    {
    “connection”: “courses”,//this being the name of the connector you added in database.js
    “kind”: “collectionType”,
    “collectionName”: “cities”,

    }
    save the file, build and run again, remember to add the role rights needed.
    this will make it seem like the data is stored in the same database, although it is running from the same api, the data will then be stored in the courses database.
    hope this helps
1 Like

Thanks for answer!

I will try that approach, sounds like a good idea!

please take note of the following post: Multiple DB, Multiple Strapi Instances, Role Permissions
not sure if you might be using multiple Strapi instances, if you are, here is a problem I have encountered.

Can just confirm that this works flawless. Thanks again!

1 Like

When you say "remember to add the role rights needed, you re talking about copying the collections (e.g. strapi_premission) into the new database?

Hello Fredrik, where did you add/change the roles and permissions to make this work?
Thanks!

Matias

welcome to the Strapi Community,
and that’s correct yes,
So how I do it is, I copy the following tables: 'users-permissions_permission, users-permissions_role, strapi_permission, strapi_roleandstrapi_administrator`
Hope this helps