Multi-Tenancy with Nodejs and mongoDb

The main concept of multi-tenancy is privacy and data segregation, With MongoDB architecture ( Database and collections ). It’s easy to allocate collection for tenants database

You should have a simple npm application setup and install mongoose by …


This content originally appeared on DEV Community and was authored by Code Salley

The main concept of multi-tenancy is privacy and data segregation, With MongoDB architecture ( Database and collections ). It’s easy to allocate collection for tenants database

Erb diagram

You should have a simple npm application setup and install mongoose by running;

npm install mongoose --save

Implement a logic to handle MongoDB database connection and switching. In this scenario I will use two different approaches, switching between database's using useDb and disconnect and reconnect ( this is useful for test cases only )

Connect and disconnect approach


// mongoose import 
const Mongoose = require('mongoose')

// a function that takes database name and database url as import and return a mongoose connection
const connectDb = async (dbName, dbUrl) => {

if (dbName === Mongoose.connection?.db?.databaseName) return Mongoose

  try {
    Mongoose.connection.close()
    const mongoose = await Mongoose.connect(dbUrl, { useNewUrlParser: true })
    mongoose.connection.once('open', () =>
      log.info(`mongodb connected to ${dbUrl}`)
    )
    return mongoose
  } catch (error) {
    log.error(error)
  }
}
module.exports = { connectDb }

with the above usage, all we need is the database name and database URL, We check the database name to see if it's already open, if open we just return mongoose object else we close all open connections and reconnect to the database using the URL we passed in.

useDb(recommended) approach


// mongoose import 
const Mongoose = require('mongoose')

// a function that takes database name and database url as import and return a mongoose connection
const connectDb = async (dbName, dbUrl) => {

if (dbName === Mongoose.connection?.db?.databaseName) return Mongoose

  try {
    if( Mongoose.readyState == 1 ) {
        return Mongoose.useDb(dbName)
    } else {
    const mongoose = await Mongoose.connect(dbUrl, { 
                           useNewUrlParser: true })
    mongoose.connection.once('open', () =>
      log.info(`mongodb connected to ${dbUrl}`)
    )
    return mongoose.useDb(dbName)
}

  } catch (error) {
    log.error(error)
  }
}
module.exports = { connectDb }

A very simple approach, with useDb all we need is an open connection or create a new connection then return a new instance of MongoDB by passing the database name to the useDb function from an open MongoDB connection. In other cases you might have separate models(schema) for tenants, Here is an example.

// connect to mongodb
const mongoose = await Mongoose.connect(dbUrl, { 
                           useNewUrlParser: true })

// connect to prefer database
const db =  mongoose.useDb(databaseName)

// use model(schema) preferred
db.model(modelName, schema)

Keep tenants locked up!!

twitter: code salley


This content originally appeared on DEV Community and was authored by Code Salley


Print Share Comment Cite Upload Translate Updates
APA

Code Salley | Sciencx (2021-10-29T19:04:55+00:00) Multi-Tenancy with Nodejs and mongoDb. Retrieved from https://www.scien.cx/2021/10/29/multi-tenancy-with-nodejs-and-mongodb/

MLA
" » Multi-Tenancy with Nodejs and mongoDb." Code Salley | Sciencx - Friday October 29, 2021, https://www.scien.cx/2021/10/29/multi-tenancy-with-nodejs-and-mongodb/
HARVARD
Code Salley | Sciencx Friday October 29, 2021 » Multi-Tenancy with Nodejs and mongoDb., viewed ,<https://www.scien.cx/2021/10/29/multi-tenancy-with-nodejs-and-mongodb/>
VANCOUVER
Code Salley | Sciencx - » Multi-Tenancy with Nodejs and mongoDb. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/29/multi-tenancy-with-nodejs-and-mongodb/
CHICAGO
" » Multi-Tenancy with Nodejs and mongoDb." Code Salley | Sciencx - Accessed . https://www.scien.cx/2021/10/29/multi-tenancy-with-nodejs-and-mongodb/
IEEE
" » Multi-Tenancy with Nodejs and mongoDb." Code Salley | Sciencx [Online]. Available: https://www.scien.cx/2021/10/29/multi-tenancy-with-nodejs-and-mongodb/. [Accessed: ]
rf:citation
» Multi-Tenancy with Nodejs and mongoDb | Code Salley | Sciencx | https://www.scien.cx/2021/10/29/multi-tenancy-with-nodejs-and-mongodb/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.