Plug multiple SQL databases

It's becoming quite common to have multiple databases when building a web application. Especially when designing your app with micro services.

Whenever possible, we strongly advice to have one and only one SQL database to facilitate native joins between your relationships.

Lumber relies on the Sequelize ORM to access and manipulate your data. With Sequelize, you can easily connect to multiple databases and create your models accordingly.

1. Update the models/index.js file

To do so, you first need to update the file models/index.js which is where the logic to connect to the database(s) and load your models is implemented.

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
let dbs = [{
name: 'demo',
connectionString: process.env.DATABASE_DEMO
}, {
name: 'billing',
connectionString: process.env.DATABASE_BILLING
let sequelize = {};
let db = {};
let models = {};
dbs.forEach((info) => {
models[] = {};
let databaseOptions = {
logging: console.log,
pool: { maxConnections: 10, minConnections: 1 },
dialectOptions: {}
if (process.env.DATABASE_SSL) {
databaseOptions.dialectOptions.ssl = true;
if (process.env.DATABASE_ENCRYPT) {
databaseOptions.dialectOptions.encrypt = true;
let connection = new Sequelize(info.connectionString, databaseOptions);
sequelize[] = connection;
.filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== 'index.js');
.forEach(function (file) {
try {
var model = connection['import'](path.join(__dirname,, file));
sequelize[] = model;
models[][] = model;
} catch (error) {
console.error('Model creation error: ' + error);
Object.keys(models[]).forEach(function(modelName) {
if ('associate' in models[][modelName]) {
db.Sequelize = Sequelize;
db.sequelize = sequelize;
module.exports = db;

Between the line 5 and 11, edit the dbs variable according to your databases. In this example, we have two databases.

  • demo where the connection string is set to the environment variable DATABASE_DEMO

  • billing where the connection string is set to the environment variable DATABASE_BILLING

You're free to use any alias in the name option but you need to make sure the connectionString value is set to a database connection string.


2. Create a directory for each database's models

At the moment, you should have a models/ directory that looks like this:

Command line
ls -l models

Move all your models file to a directory named exactly by the database alias name you chose on the models/index.js file (Step 1). In our case here, it's demo.

Command line
tree models

Make sure you keep the index.js file in the models/ directory.

Then, create a directory for each of your database and create the Sequelize models that map your tables.

You can take inspiration from the existing models to create your new ones or read the Sequelize documentation about Model definition.

module.exports = (sequelize, DataTypes) => {
const Model = sequelize.define('billings', {
'customer_id': {
type: DataTypes.INTEGER,
'VAT': {
type: DataTypes.STRING,
'address': {
type: DataTypes.STRING,
'zip_code': {
type: DataTypes.STRING,
'state': {
type: DataTypes.STRING,
'city': {
type: DataTypes.STRING,
}, {
tableName: 'billings',
underscored: true
Model.associate = (models) => {
return Model;

3. Update the Forest middleware options

You need to indicate to the Forest middleware all the database connections. To do so, update the middlewares/forestadmin/index.js file and add/change the options sequelize and connections.

const models = require('../../models');
const requireAll = require('require-all');
module.exports = function (app) {
require('lumber-forestadmin').run(app, {
modelsDir: __dirname + '/../../models',
envSecret: process.env.FOREST_ENV_SECRET,
authSecret: process.env.FOREST_AUTH_SECRET,
sequelize: models.Sequelize,
connections: [
dirname: __dirname + '/../../routes',
recursive: true,
resolve: Module => app.use('/forest', Module)

4. Replace models.<modelName> everywhere

You can't use the syntax models.<modelName> anymore to trigger CRUD operations on your data. On our example, the action Mark as live is broken.

POST /forest/actions/mark-as-live 500 10.501 ms - 3264
TypeError: Cannot read property 'update' of undefined
at (/Users/seyz/workspace/lumber-projects/QuickStart/routes/companies.js:14:6)

To fix this issue, we have to import the databases' connections on top of each file and change the syntax of the models' references like this:

const express = require('express');
const router = express.Router();
const Liana = require('forest-express-sequelize');
const models = require('../models');
// ...
// Declare the database connections.
const dbDemo = models.sequelize.demo.models;
const dbBilling = models.sequelize.billing.models;'/actions/mark-as-live', Liana.ensureAuthenticated, (req, res) => {
let companyId =[0];
return dbDemo.companies // Change the syntax here.
.update({ status: 'live' }, { where: { id: companyId }})
.then(() => res.send({ success: 'Company is now live!' }));

Create a relationship between two models from different databases

The main problem of having two databases is that you cannot rely on SQL joins anymore to browser your data over relationships.

To fix that, we will create a Smart Relationship and code the logic to reconcile the data between our Customers (database demo) and Billings (database: billings).

const Liana = require('forest-express-sequelize');
const models = require('../models');
const dbBilling = models.sequelize.billing.models;
Liana.collection('customers', {
fields: [{
field: 'billing',
type: 'String',
reference: '',
get: function (customer) {
return dbBilling.billings.findOne({ customer_id: });

And of course, you can create the inverse relationship:

const Liana = require('forest-express-sequelize');
const models = require('../models');
const dbDemo = models.sequelize.demo.models;
Liana.collection('billings', {
fields: [{
field: 'customer',
type: 'String',
reference: '',
get: function (billing) {
return dbDemo.customers.findOne({ id: billing.customer_id });