Are there any better ways other than including require ('mongoose') in every model file?

I need mongoose in the main app.js file once. can i pass it to the user.

var mongoose = require('mongoose');

      

without downloading it again? in each file. doesn't the script do the extra work every time I need the same module?

var User = require('./models/user')

      

+3


source to share


2 answers


From node documentation

Modules are cached after the first time they are loaded. This means (among other things) that every call required ('foo') will receive exactly the same object that would be returned if it resolved the same file.

Multiple calls that require ('foo') cannot cause module code to be executed multiple times.



Take a look at Caching .

You can still use the mongoose module globally. Instead, var mongoose = require('mongoose');

just write mongoose = require('mongoose');

. Then you will be able to access the mongoose from any other module.

+3


source


If coffeescript is used, you must explicitly add the globals object.

The utils file globally requires everything you need:

//utils.js

globals['mongoose] = require('mongoose');
globals['fs'] = require('fs-extra');

      



Now, in all your scripts, you only need to require the utils.

require('./utils');

console.log('fs is ' + fs);
console.log('mongoose is ' + mongoose);

      

I often use this when creating service files, but I had no need to use it.

0


source







All Articles