I am creating an Express application and using Mongoose to save data.
I created a User model (username&password). It needs to be able to be saved. So I use require('mongoose') in Models/user-model.js. In the route for User I want to be able to get all the users or just find some. So I need to require('mongoose') there as well. Also in the main js file (app.js) I create a connection to the database so there is a require('mongoose') there as well.
It all works well, but is it the best way to require mongoose in all of these files? Or is there a better way to do this?
Well, "best" is hard to say for certain. But, what you're doing is a common-enough practice and should be fine in most cases.
The 1st time mongoose is required, it'll be cached for subsequent requires:
Modules are cached after the first time they are loaded. This means (among other things) that every call to
require('foo')will get exactly the same object returned, if it would resolve to the same file.Multiple calls to require('foo') may not cause the module code to be executed multiple times. [...]
With module caching in mind...do you think that is a good idea to create a global APP object and store things like models and libraries in the bootstrap and then just pass that object to other modules or just require the module dependencies when it needed no matter if our modules have a lot of require() sentences ?