Sequelize没有正确加载数据库表

时间:2015-02-09 16:47:52

标签: sequelize.js

我有一个快速服务器,它确实:

app.db = SequelizeData config.db
app.db.sequelize.sync({force: false}).complete (err) ->
  console.log err
  console.log 'Initialzed database on:'
  console.log config.db

SequelizeData是:

(function() {
  'use strict';
  var Sequelize, fs, path, _;

  _ = require('lodash');

  fs = require('fs-extra');

  path = require('path');

  Sequelize = require('sequelize');

  module.exports = function(config) {
    var db, files, modelPath, myDb, sequelize;
    sequelize = new Sequelize(config.database, config.username, config.password, {
      dialect: 'postgres',
      host: config.host,
      port: config.port,
      logging: false,
      define: {
        charset: 'utf8',
        collate: 'utf8_general_ci'
      }
    });
    db = {};
    modelPath = __dirname + "/models";
    files = fs.readdirSync(modelPath);
    _.each(files, function(file) {
      var model;
      if ('.coffee' === path.extname(file)) {
        model = sequelize["import"](path.join(modelPath, file));
        return db[model.name] = model;
      }
    });
    Object.keys(db).forEach(function(modelName) {
      if ('associate' in db[modelName]) {
        return db[modelName].associate(db);
      }
    });
    myDb = _.assign(db, {
      sequelize: sequelize,
      Sequelize: Sequelize
    });
    return myDb;
  };

}).call(this);

基本上遍历我的模型并将它们添加到sequelize。但是,虽然我的数据库存在,但它不会创建任何表。我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

您确定可以实际需要* .coffee文件吗?您应确保导入实际正在运行。

您可能需要进行Sequelize.sync({force:true})调用才能让Sequelize删除现有表并重新创建它们。您需要在每次架构更改时执行此操作,或手动更改架构。

您还可以设置logging: true以查看正在发送的特定SQL命令。

ps:这是Node:您不需要将模块包装在闭包中:只需将它们放在自己的文件中并require()