2017-08-18 104 views
0

这是我第一次使用Sequelize并试图获得一个教程工作。节点Sequelize。 TypeError

我最初使用mysql,但我得到一个错误,以更新到mysql2,我做到了。

我得到下面的错误。

任何人都可以看到我做错了什么?

错误:

node_modules/sequelize/LIB/sequelize.js:380

this.importCache [路径] = defineCall(此,数据类型);

类型错误:defineCall不是一个函数

part of package.json 
"dependencies": { 
    "body-parser": "^1.17.2", 
    "dotenv": "^4.0.0", 
    "ejs": "^2.5.7", 
    "express": "^4.15.3", 
    "express-session": "^1.15.5", 
    "md5": "^2.2.1", 
    "multer": "^1.3.0", 
    "mysql": "^2.14.1", 
    "mysql2": "^1.4.1", 
    "node-datetime": "^2.0.0", 
    "nodemailer": "^4.0.1", 
    "passport": "^0.4.0", 
    "passport-local": "^1.0.0", 
    "password-hash": "^1.2.2", 
    "random-string": "^0.2.0", 
    "sequelize": "^4.5.0" 
} 


app.js 
var models = require("./models"); 
models.sequelize.sync().then(function() { 
    console.log('Nice! Database looks fine') 
}).catch(function(err) { 
    console.log(err, "Something went wrong with the Database Update!") 
}); 

/models/index.js 
"use strict"; 

var fs = require("fs"); 
var path = require("path"); 
var Sequelize = require("sequelize"); 
var env = process.env.NODE_ENV || "development"; 
var config = require(path.join(__dirname, '..', 'config', 'config.json'))[env]; 
var sequelize = new Sequelize(config.database, config.username, config.password, config); 
var db = {}; 


fs 
    .readdirSync(__dirname) 
    .filter(function(file) { 
     return (file.indexOf(".") !== 0) && (file !== "index.js"); 
    }) 
    .forEach(function(file) { 
     var model = sequelize.import(path.join(__dirname, file)); 
     db[model.name] = model; 
    }); 

Object.keys(db).forEach(function(modelName) { 
    if ("associate" in db[modelName]) { 
     db[modelName].associate(db); 
    } 
}); 


db.sequelize = sequelize; 
db.Sequelize = Sequelize; 

module.exports = db; 

回答

3

models/文件夹内的每个文件除了index.js由该行加载。

var model = sequelize.import(path.join(__dirname, file)); 

实际情况是,Sequelize逐个加载每个模块并调用每个模块导出的函数。 Sequelize期望您导出一个带有两个参数的模块,即Sequelize对象和数据类型对象。

function User(sequelize, DataTypes) { 
    return sequelize.define('users', { 
    // ... 
    }); 
} 

exports = module.exports = User; 

如果你有在模型文件夹中多余的文件不匹配的格式,然后Sequelize不知道他们做什么。 models/文件夹中还有其他什么文件?

+0

谢谢!为了指出这一点,出现了一个流氓文本文件,我删除了它,现在错误消失了。 如果我需要在模型文件夹中包含更多文件,我需要做什么? 你能举个例子吗? – pigfox

+0

你可以创建一个文件数组来忽略你的'index.js'和'filter'调用,你可以遍历忽略文件以确保在整个数组中找不到它。 :)。 'const忽略= ['index.js','credentials.txt','sqlite.db'];'如果您使用Lodash,您可以在'filter'中执行'!_。includes(ignored,file)'等操作。呼叫。 –

+0

很酷,谢谢! – pigfox

相关问题