Search code examples
javascriptnode.jsmongodbmongoosemicroservices

Share mongo models across multiple apps


I'm building an app and as it grows, i learn more and grow with it.

At the moment i've split my app into 3 seperate pieces

  1. Web - front end
  2. API - data
  3. Worker - data processing

each of these seperate nodejs apps have a function to perform while being on different servers.

I started another little package/app that includes shared code and then included it in the dependancies as such :

"shared": "file:../shared",

so that i can access my models from any app whenever i please as such :

let User = require('shared/models/user')

I find my self running the following command to upgrade to latest models while in development mode ALOT

yarn upgrade shared

I'm still learning about best practices and all that...is this really the best way of doing this? Should i be doing something else to save some more time?

Any help would be greatly appreciated!


Solution

  • Sharing the same model across the microservices is not a very good architectural decision. A Microservice should own its models and sharing is the opposite of owning.

    This doesn't mean that one cannot have Users in multiple microservices but not the same model. You can use a integration pattern, i.e. Anti-corruption layer. Long-story short, the canonical model contains all the fields but remote models contain only the needed subset of fields.