Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - passing object with require

Tags:

node.js

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?

like image 983
Alexander Mills Avatar asked Feb 12 '23 09:02

Alexander Mills


2 Answers

module.exports = function (mongoose) {
  // . . .
  return model;
};
like image 150
generalhenry Avatar answered Feb 19 '23 15:02

generalhenry


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);
like image 23
A.B Avatar answered Feb 19 '23 16:02

A.B