带有 sequelize 的 ExpressJs

ExpressJs with sequelize

我已成功将 Sequelize ORM 与 Express Js 集成,但我无法在 sequelize 中迁移数据库。有帮助吗?

var express = require('express');
var Sequelize = require('sequelize');
var bodyParser =  require('body-parser');
var app = express();

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

var router = express.Router();
var sequelize = new Sequelize('tousif', 'root', 'root', {
  host: 'localhost',
  dialect: 'mysql'
});

为了使用 CLI,您需要安装相应的软件包:

npm install --save sequelize-cli

可以通过帮助命令获取有关可用命令的更多详细信息:

$ sequelize help:init
$ sequelize help:db:migrate
$ sequelize help:db:migrate:undo

有关更多信息,请使用此 link Sequelize

你加载模型并同步数据库了吗?您的代码并没有真正向我显示您的其余配置,只是连接字符串。

我建议您在安装 sequelize-cli 后使用

$ sequelize help:model:create

它将告诉您如何创建模型。

您必须导入模型文件、关联方法、将这些模型与数据库同步。

  // Expose the connection function
  db.connect = function(database, username, password, options) {
  if (typeof db.logger === 'function')
    console.log("Connecting to: " + database + " as: " + username);

  // Instantiate a new sequelize instance
  var sequelize = new db.Sequelize(database, username, password, options);

  db.discover.forEach(function(location) {
    var model = sequelize["import"](location);
    if (model)
      db.models[model.name] = model;
  });

  // Execute the associate methods for each Model
  Object.keys(db.models).forEach(function(modelName) {
    if (db.models[modelName].options.hasOwnProperty('associate')) {
      db.models[modelName].options.associate(db.models);
      winston.info("Associating Model: " + modelName);
    }
  });

  if (config.db.sync) {
    // Synchronizing any model changes with database.
    sequelize.sync(
      //{ force: true } // use to drop before create
      ).then(function() {
        console.log("Database synchronized");
      }).catch(function(err) {
        console.log(err);
      });
  }
}