In an attempt to modulate a large existing Node + Express + Mongoose application into several mountable applications, each of which is designed as a separate NPM package, we are wondering if one Mongo example should be used between them - is it a good idea?
Let's say we have a package of NPM packages, each of which contains client-side assets, Mongoose models and REST-APIs implemented using Express. They share several common features, but essentially reusable artifacts should be considered separately. An Express-based host application also sets these under various root URIs:
var discussions = require('discussions'), tickets = require('tickets'), events = require('events'), express = require('express'), app = express(); var environment = { ...see below... }; ... app.use('/events-api', events(environment)); app.use('/tickets-api', tickets(environment)); app.use('/discussions-api', discussions(environment));
Now, since the events , tickets and discussions applications (NPM pulled individual packages through the host package.json ), use Mongoose, like the host application, we decided that we will go to the Mongoose instance of the host through some environment object, which also includes others that the host wants to share with installed applications.
Do you see any obvious flaws in this approach? Installed applications in this case do not specify Mongoose as a dependency in their respective package.json , and they will not require('mongoose') as usual, but instead get a Mongoose instance from the host that is responsible for connecting to MongoDB.
If this is a bad idea and you suggest that each sub-application declare dependency on Mongoose on its own, each NPM package will receive its own copy of Mongoose and each of them should connect to MongoDB, right?
Some background information:
- We really want to include applications in the host application, run in one process, and not with multiple Node instances. The host contains authentication middleware and other things.
- We want to have applications as separately developed NPM packages, including as versions depending on the various host applications that we create, and not just copy the source code into the main application.
- We understand that reusing a single Mongoose instance between multiple installed applications will have the same model namespace.
Edit: To clarify the structure of the package after everything was npm install ed:
host/ assets/ models/ routes/ node_modules/ express/ ... mongoose/ ... events/ assets/ ... models/ ... routes/ ... tickets/ assets/ ... models/ ... routes/ ... discussions/ assets/ ... models/ ... routes/ ...
That is, the events , tickets and discussions applications do not include Mongoose (or Express), but they are designed to rely on a constantly present host application that provides these dependencies.
We assume that an NPM package, such as tickets , cannot just require material from the parent, right?