简体   繁体   中英

is there better ways other than including require('mongoose') in every models file?

i require mongoose in main app.js file once. can i pass it to User.

var mongoose = require('mongoose');

without loading it again? in each file. doesn't script do extra job each time i require same module?

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

From node documentation

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.

Take a look at Caching .

It is still possible to require mongoose module globally. Instead of var mongoose = require('mongoose'); just write mongoose = require('mongoose'); . Then you will be able to access mongoose from any other module.

If you are using coffeescript, then you must explicitly add to the globals object.

In a utils file, globally require all the stuff you need:

//utils.js

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

Now in all your scripts you will only need to require the utils file. :

require('./utils');

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

I use this frequently when creating testing utility files, but I haven't had the need to use it production.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM