Sequelize更新到v4抛出错误:models.User似乎是一个函数

时间:2017-08-09 14:23:33

标签: typescript sequelize.js

我最近从续集ORM的v3更新到v4。我已按照升级指南进行操作,但仍面临问题。我的基础是express-example

这是 models / index.ts

export var db: DbConnection = {};
export var sequelize = new Sequelize(process.env.DB_CONNECTION_STRING);
var basename = path.basename(module.filename);
fs
    .readdirSync(__dirname)
    .filter(function (file) {
        return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
    })
    .forEach(function (file) {
        var model = sequelize['import'](path.join(__dirname, file));
        db[model['name']] = model;
    });

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

db['sequelize'] = sequelize; db['Sequelize'] = Sequelize;

export default <DbConnection>db;

这里是 models / user.ts

export default function defineUser(sequelize: Sequelize.Sequelize, DataTypes) {
  var User = sequelize.define<UserInstance, UserAttributes>('User', {
    email: {
      type: DataTypes.STRING,
      unique: true,
      validate: { isEmail: true }
    },
    password: DataTypes.STRING,
    role: {
      type: DataTypes.ENUM,
      values: ['Admin', 'Operator', 'Member']
    }
  });

  User.beforeCreate(function (user: UserInstance, options) {
    return hashPassword(user.password).then(function (hashedPw) {
      user.password = hashedPw;
    });
  })
  return User;
};

function hashPassword(password: string): Promise<string> {
  return new Promise(function (resolve, reject) {
    bcrypt.genSalt(5, function (err, salt) {
      if (err) { reject(err); }

      bcrypt.hash(password, salt, null, function (err, hash) {
        if (err) { reject(err); }
        resolve(hash);
      })
    });
  })
};

但是,我仍然会收到错误:

  

未处理的拒绝错误:models.User似乎是一个函数。也许您正在导入模型工厂功能?然后,您应该使用sequelize.import创建模型,请参阅https://github.com/sequelize/express-example/blob/master/models/index.js#L17       在Loader.loadFixture(C:\ Users \ George \ Source \ Repos \ myProj \ node_modules \ sequelize-testing-fixtures \ lib \ loader.js:39:15)

我做错了什么?

更新

我也试过module.exports = function defineUser(...,但这也不起作用。

1 个答案:

答案 0 :(得分:0)

您可能想要修复电子邮件和密码的数据类型。您也可以使用module.export而不是函数。

email: {
  type: Sequelize.STRING, //change to DataTypes.STRING
  unique: true,
  validate: { isEmail: true }
},
password: Sequelize.STRING, //change to DataTypes.STRING
role: {
  type: DataTypes.ENUM,
  values: ['Admin', 'Operator', 'Member']
}