简体   繁体   中英

Node.js - passing object with require

I am pretty certain there is a way to pass a variable using require.

So it would look something like this:

var model = require('model')(mongoose);

With the above line of code, I want to pass my model file my database information (mongoose), so that if I access the same model with a different database, I can pass it different database information.

However, even if the above syntax is correct, I am not sure what my model file itself would have to look like. Can anyone help me out with this?

module.exports = function (mongoose) {
  // . . .
  return model;
};

You can pass moongoose by argument to that file

var model = require('model')(mongoose);

Your module will look like this, you can make an object in module.exports and can attach multiple properties to that object and in the end return it from the function

 module.exports = function (mongoose) {
  model ={};
  model.properties = {};
 model.yourfunction1 = function(){};

  return model;
};

I guess I can't assign anything else to module.exports in this case?

Answer to your comment is explained below

Choosing between module.exports and exports depends on you

For exports

exports.object1 = {};
exports.object2 = {};

For module.exports

module.exports = function(){
myobj={}
myobj.object1 = {};
myobj.object2 = {};
return myobj
}

Now calling it will be different

For exports it will be directly available on file variable

var file = require('./file');
console.log(file.object1);

For module.exports you will execute it like a function by appending function parenthesis so that object can be returned

 var file = require('./file')();
console.log(file.myobj.object1);

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