TypeError:无法读取未定义的属性“ define”

时间:2018-12-23 10:12:58

标签: node.js sequelize.js

我尝试将Db从mongodb更改为mysql,我使用sequelize而不是mongoose,但出现此错误,我以sequelize格式创建了User.js模型,但出了点问题,我不知道为什么

const User = sequelize.define('users', {
                   ^

TypeError: Cannot read property 'define' of undefined"

这是我的代码:

server.js

const Sequelize = require('sequelize');       
// DB Config
const db = require('./config/keys');
// Connect to MySql
const sequelize = new Sequelize(db.database, db.user, db.password, {
    host: db.host,
    dialect: 'mysql',
    port: db.port
});

// Test the connection
sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });    
const serverDB = {};
serverDB.sequelize = sequelize;
serverDB.Sequelize = Sequelize;
module.exports = serverDB;

Users.js

const serverDB = require('../server');
const sequelize = serverDB.sequelize;
const Sequelize = serverDB.Sequelize;

const User = sequelize.define('users', {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        name: {
            type: Sequelize.STRING,
            allowNull: false
        },
        email: {
            type: Sequelize.STRING,
            allowNull: false
        },
        password: {
            type: Sequelize.STRING,
            allowNull: false
        },
        avatar: {
            type: STRING
        },
        date: {
            type: Sequelize.DATE,
            defaudefaultValue: Sequelize.NOW
        }
    });

sequelize.models.modelName

// sequelize.sync()
//     .then(() => {
//         console.log('User db and user table have been created')
//     });

module.exports = User;

1 个答案:

答案 0 :(得分:0)

您应该添加

const Sequelize = require('sequelize');

在您的客户中也是如此。

并且仅导出并使用小写的sequelize

并确保server.js的相对路径正确。