Plug multiple NoSQL databases

Below you'll find a couple steps to plug multiple mongoose databases into a single Forest Admin project.

Forest Admin supports MongoDB databases. The ORM used is Mongoose.

1. Install Forest Admin with 1 database

Even if you want to use multiple databases, install with 1 of them. You'll plug your other databases later.

2. Move your models

Move the content of the models folder into a new sub-folder that matches your db name (db1):

├── db1/
│ ├── index.js
│ ├── model1.js
│ └── model2.js

3. Create a new connection.js file

In your new db1 folder, add a new connection.js file with the following content:

const mongoose = require('mongoose');
const connection = mongoose.createConnection(process.env.DATABASE_URL, { useNewUrlParser: true });
module.exports = connection;

This will generate one of the several connections we'll need.

4. Update your models

Update your existing models by adding the created connection:

const mongoose = require('mongoose');
const connection = require('./connection');
const schema = mongoose.Schema({
// Your existing model
module.exports = connection.model('model1', schema, 'model1');

You should remove the index.js file, which is now unnecessary.

5. Repeat steps 2 to 4

For each new database you need to plug into your project, repeat above steps 2 to 4.

In connection.js, be sure to use the DATABASE_URL of the database to plug, instead of process.env.DATABASE_URL(which is the DATABASE_URL of the database you used to install)

After adding a second database, your folder architecture should look like this:

├── db1/
│ ├── connection.js
│ ├── model1.js
│ └── model2.js
├── db2/
│ ├── connection.js
│ ├── model3.js
│ └── model4.js

6. Final step: declare your connections

Finally, update your middlewares/forestadmin/index.js to include the 2 connections:

const db1 = require('../../models/db1/connection');
const db2 = require('../../models/db2/connection');
module.exports = function (app) {
require('lumber-forestadmin').run(app, {
modelsDir: __dirname + '/../../models',
envSecret: process.env.FOREST_ENV_SECRET,
authSecret: process.env.FOREST_AUTH_SECRET,
mongoose: require('mongoose'),
connections: [