danielad danielad - 2 months ago 8
Javascript Question

passing parameters to module.exports in nodejs

I have the following code for implemetation of nodejs a rest api.


var connection = require('./database_connector');
connection.initalized(); //guys connection is i want to pass a connection varible to the model
var peson_model = require('./models/person_model')(connection); //this not working
var app = express();
app.use(bodyparser.urlencoded({extended: true}));
app.get('/persons/', function(req, res) {
person_model.get(res); // retrive get results
// .............express port and listen

is a model class that is supposed to retrieve based on the http verb. For example
retrieves the following and currently has a single method as follow.

function Person(connection) {
this.get = function (res) {
connection.acquire(function(err, con) {
con.query('select * from person limit 3', function(err, result) {
console.log("get called");
// ** I want to pass a connection variable to the model
module.exports = new Person(connection);

In the code above,
var peson_model = require('./models/person_model')(connection);
is not working.

How do I pass the connection variable and export the module?


If you return a function from your export, you can pass your parameter.

module.exports = function(connection) {
    return new Person(connection);

You will need to set this.connection and use that inside your function though.