lundi 14 août 2017

Mongoose: handling multiple databases when working with one model

What I want is to have arbitrary databases (50 for example) with the same collections (same schemas, exact models, different data) and 1 nodejs (expressjs + mongoose) web app.

Example simplified case:

I have:

  • a single web application (expressjs + mongoose) with User model.
  • 50 domains 50 databases with users collection.

What behaviour I want to achieve:

  • GET /api/users/ http request is coming to one of domains (test-domain-39.myapp.com)
  • app gets the requested domain name (test-domain-39) and somehow mongoose understands that it wants to query database-39 when I just do User.find({isActive: true}) in users.controller

So I just want an abstraction. I pass db name to mongoose and continue to work with the User model (as we all usually do when having single DB connection) and mongoose, if needed, creates connection (if it's the first request to the specific db), keeps it alive for next requests in connection pool and etc.

What's the most simple and efficient way to accomplish that?

Thank's in advance!

Aucun commentaire:

Enregistrer un commentaire