Sequelize与Nodejs

时间:2016-07-11 17:57:41

标签: javascript mysql node.js sequelize.js

我在使用NodeJs连接SEQUELIZE(mysql)时遇到了问题。虽然已建立连接但模型配置不正确。我使用这种方法 -

./config/sequelize-conn.js

'use strict';
var sequelize  = function (config, Sequelize) {
var sql = new Sequelize(config.mysql.db, config.mysql.user, config.mysql.pass, {
    host:        config.mysql.host,
    dialect:     'mysql', //|'sqlite'|'postgres'|'mssql'
    pool:        {
        max:  5,
        min:  0,
        idle: 10000
    },
    //logging:     true,
    underscored: true
});
sql
    .sync({force: true})
    //.authenticate()
    .then(function () {
        console.log('Connection has been established successfully with mysql.');
    }, function (error) {
        console.log('Connection with mysql failed.', error);
    });
return sql;
};
module.exports = sequelize;

//server.js

var sequelize     = require('sequelize');
var sqlConnection = require('./config/sequelize-conn')(config, sequelize);

我希望以这种方式直接使用模型..

models/HotelGroup.js

var Sequelize  = require('sequelize');
var sequelize  = require('../../config/sequelize-conn');
var HotelGroup = Sequelize.define('hotel_chains', {
    id:         {
        type:          Sequelize.INTEGER(11),
        allowNull:     false,
        primaryKey:    true,
        autoIncrement: true
    },
    hotel_name: {
        type:      Sequelize.STRING,
        allowNull: false
    },
    hotel_code: {
        type:      Sequelize.STRING,
        allowNull: false
    },
    status:     {
        type:         Sequelize.BOOLEAN,
        allowNull:    false,
        defaultValue: '1'
    }
}, {
    tableName:       'hotel_chains',
    timestamps:      false,
    paranoid:        true  // Model tableName will be the same as the model name
});
module.exports = HotelGroup;

它给我的错误是sequelize.define不是一个函数。

虽然连接正在建立,但是当我尝试使用require访问服务文件中的任何模型时。它打破了此错误消息。我做错了。

1 个答案:

答案 0 :(得分:1)

我认为你需要使用sequelize的实例,而不是类。所以sequelize.define 不是 Sequelize.define

此外,您需要正确实例化它:var sequelize = new Sequelize(...)