Javascript 将参数传递给nodejs中的module.exports

Javascript 将参数传递给nodejs中的module.exports,javascript,node.js,express,Javascript,Node.js,Express,我有以下用于实现RESTAPI的nodejs的代码。 app.js 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); //

我有以下用于实现RESTAPI的nodejs的代码。
app.js

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.use(bodyparser.json());
app.get('/persons/', function(req, res) {
    person_model.get(res); // retrive get results
});
// .............express port and listen
person\u model.js
是一个模型类,应该基于http谓词进行检索。例如,
person.get
检索以下内容,当前有一个方法,如下所示

function Person(connection) {
    this.get = function (res) {
        connection.acquire(function(err, con) {
            con.query('select * from person limit 3', function(err, result) {
                con.release();
                console.log("get called");
                res.send(result);
            });
        });
    };
}
// ** I want to pass a connection variable to the model
module.exports = new Person(connection);
在上面的代码中,
var-peson_model=require('./模型/人_model')(连接)不工作


如何传递连接变量并导出模块?

如果从导出返回函数,则可以传递参数

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

您需要设置
此.connection
并在函数中使用它。

如果您从导出返回函数,则可以传递参数

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

您需要设置此连接,并在函数中使用此连接。

是否有任何方法可以传递连接变量隐式而非显式含义,而不是每次我希望它在应用程序范围内使用时在不同型号中共享它。一次创造。我非常感谢您的回答如果用户在发出require('./lib.js')时忘记包含(连接),您如何发送正确的错误消息?我试着在函数中加入“if connection===undefined then throw”,就像你上面所说的那样,但是这个throw没有被执行……嗨,这个
连接是从哪里来的?有没有什么方法可以让我传递连接变量隐式而非显式的含义,而不是每次我希望它在应用程序范围内时在不同的模型之间共享它。一次创造。我非常感谢您的回答如果用户在发出require('./lib.js')时忘记包含(连接),您如何发送正确的错误消息?我试着在函数中加入“if connection===undefined then throw”,就像上面那样,但没有执行该抛出操作…嗨,这个
连接是从哪里来的?