how to reuse mongoose model in multiple projects in the elegant way how to reuse mongoose model in multiple projects in the elegant way mongodb mongodb

how to reuse mongoose model in multiple projects in the elegant way


I wont advice you to make a published npm package reason being, as A Good NodeJS developer you shouldn't pollute npm with packages that doesnt help anyone else. Unless you are a paid npm user with access to the private packages option.

Did you know package.json supports git urls, you can read about that @ Git URLs as Dependencies

A few examples of git urls in package.json

// github urlgit+ssh://git@github.com:example/example-repo.git#v1.0.0// bitbucket urlgit+ssh://git@bitbucket.org/example/example-repo.git#v1.0.0

My suggestion is create a separate package with an API to set config, which in a scenario like yours would be DB connection related stuff. Upload it to a private git repo and use the private git repo url in all the application. Then during the application initializing phase configure the package and use its API.

Now the applications can be build on any system which has access to the private repo and can reuse the code.

You can also put your package on a public repo in case you dont have access to a private repo, which is still better than publishing npm packages in order to shared it across your applications.


You can just create another package containing common models and push it to a private git repository or maybe a public one if you are fine with it. Then use the git repository url in package.json rather than publishing it to NPM. Let's say you named it models-repo.

It can be a simple package consisting of:

├── README.md├── index.js├── models│   ├── carLoan.js└── package.json

You can include it in your package.json file of the application using git URLs:

{ "models-repo" : "git+ssh://git@models-repo-path.git" }

Now you can require it in any file and start using it:

const models = require('models-repo');const carLoanModel = models.car_loan;//Do somethingcarLoanModel.find({})

You need to be careful with the permissions when using it in production.


You can definitely put them in a package and reuse it. And for having its own DB Ops and Network Ops, you can take the DB URL as an environment variable while starting the project. And use the same from process.env.$variable while connecting to the database.