object不是构造函数节点js

时间:2017-09-22 16:01:58

标签: node.js express

您好我正在编写以下代码,

**mysql-model.js**
var mysqlModel = require('mysql-model');

var model = function(){
var MyAppModel = mysqlModel.createConnection({
    host                        : 'localhost',
    user                        : "root",
    password                    : "",
    database                    : "test",
});
return MyAppModel;
}
module.exports = model;

**leave.js**

var dbConnectionCreator = require('../utilities/mysqlConnection.js');
var mysqlModel = require('../utilities/mysql-model.js');
var object = mysqlModel.MyAppModel;
Leave = new object({tableName: "leave_history"});

我收到以下错误

TypeError:object不是构造函数     在对象。 (C:\瓦帕\ WWW \表达-Redux的样本主\服务器\模型\ leave.js:7:9)

帮我解决问题

2 个答案:

答案 0 :(得分:0)

没有正确mysqlModel.MyAppModel,因此它是undefined。您不会将该名称的属性分配给mysql-model.js中的导出。你这样做了:

module.exports = model;

使导出对象本身成为你的函数。并且,该函数也不是构造函数,它是正常函数。

所以,编写mysql-model.js的方式,您可以这样做:

let mysqlModel = require('../utilities/mysql-model.js');
let leave = mysqlModel();

由于导出只是一个普通函数,因此您只需将其称为普通函数。

答案 1 :(得分:0)

<强>的MySQL-model.js

var mysqlModel = require('mysql-model');

var MyAppModel = mysqlModel.createConnection({
    host: 'localhost',
    user: "root",
    password: "",
    database: "test",
});

module.exports = {MyAppModel};

<强> leave.js

var dbConnectionCreator = require('../utilities/mysqlConnection.js');
var {MyAppModel} = require('../utilities/mysql-model.js');
Leave = new MyAppModel({tableName: "leave_history"});

尝试上面的代码片段,就像我得到的一样,这是一个导入/导出混乱。