迁移后的Sequelize Model不同步

时间:2016-01-27 05:28:53

标签: javascript migration sequelize.js

我能够在续集模型上成功bulkCreate

我运行了迁移,将一个名为utc_offset的列添加到该模型中。

我遇到的问题是,在重置Express服务器后,我的文件中的模型在尝试创建新实例时似乎没有新列。数据库正在显示它,但是当我将值传递给该列时,它不会为新列utc_offset添加值。

我认为它与db.sequelize.sync()有关 - 当我将选项设置为{force: true}时,它删除了模型并且不会重新创建它。

以下是我的代码:

服务器:

var express = require('express'),
    app = express(),
    api,
    db = require('./models');

api = app.listen(config.address.port, config.address.host, function () {
    var host = api.address().address,
        port = api.address().port

    console.log('API listening at http://%s:%s', host, port);
    db.sequelize.sync();
});

我的models文件夹中的index.js 'use strict';

var fs        = require('fs');
var path      = require('path');
var cls       = require('continuation-local-storage');
var namespace = cls.createNamespace('ss-transaction');
var Sequelize = require('sequelize');
Sequelize.cls = namespace;
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require('../config/config.js');
var sequelize = new Sequelize(config.db.database, config.db.username, config.db.password, {
    host: config.db.host,
    dialect: config.db.dialect,
    define: {underscored: true}
});
var db        = {};

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename);
  })
  .forEach(function(file) {
    if (file.slice(-3) !== '.js') return;
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

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

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

'课程'模型:

"use strict";

module.exports = function (sequelize, DataTypes) {

    var Lesson = sequelize.define("Lesson", {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        title: DataTypes.STRING,

    }, {
        tableName: "lessons",
    });

    return Lesson;
};

'use strict';

module.exports = {
    up: function (queryInterface, Sequelize) {
        return queryInterface.addColumn(
            'lessons',
            'utc_offset',
            Sequelize.INTEGER
        );
    },

    down: function (queryInterface, Sequelize) {
        return queryInterface.removeColumn(
            'lessons',
            'utc_offset'
        );
    }
};

BulkCreate

var lessons = [{title: "lessonA", utc_offest: 1},{title: "lessonB", utc_offest: 9}]

    Lesson.bulkCreate(lessons)
        .then(function () {
            res.sendStatus(201);
        });

1 个答案:

答案 0 :(得分:1)

迁移只会更改数据库中的表结构 - 您必须手动将utc_offset列添加到模型中