Sequelize.js: how to use migrations and sync

后端 未结 11 1437
一向
一向 2020-12-02 03:20

I\'m close to having my project ready to launch. I have big plans for after launch and the database structure is going to change -- new columns in existing tables as well as

11条回答
  •  清歌不尽
    2020-12-02 04:08

    Just learning this myself, but I think I would recommend using migrations now so you get used to them. I've found the best thing for figuring out what goes in the migration is to look at the sql on the tables created by sequelize.sync() and then build the migrations from there.

    migrations -c [migration name] 
    

    Will create the template migration file in a migrations directory. You can then populate it with the fields you need created. This file will need to include createdAt/updatedAt, fields needed for associations, etc.

    For initial table creation down should have:

    migration.dropTable('MyTable');
    

    But subsequent updates to the table structure can leave this out and just use alter table.

    ./node_modules/.bin/sequelize --migrate
    

    An example create would look like:

    module.exports = {
      up: function(migration, DataTypes, done) {
        migration.createTable(
            'MyTable',
            {
              id: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true
              },
              bigString: {type: DataTypes.TEXT, allowNull: false},
              MyOtherTableId: DataTypes.INTEGER,
              createdAt: {
                type: DataTypes.DATE
              },
              updatedAt: {
                type: DataTypes.DATE
              }
            });
        done();
      },
      down: function(migration, DataTypes, done) {
        migration.dropTable('MyTable');
        done();
      }
    

    To redo from start:

    ./node_modules/.bin/sequelize --migrate --undo
    ./node_modules/.bin/sequelize --migrate
    

    I'm using coffee to run a seed file to populate the tables after:

    coffee server/seed.coffee
    

    This just has a create function in it that looks something like:

    user = db.User.create
      username: 'bob'
      password: 'suruncle'
      email: 'bob@bob.com'
    .success (user) ->
      console.log 'added user'
      user_id = user.id
      myTable = [
        field1: 'womp'
        field2: 'rat'
    
        subModel: [
          field1: 'womp'
         ,
          field1: 'rat'
        ]
      ]
    

    Remember to take your sync() out of index in your models or it will overwrite what the migrations and seed do.

    Docs are at http://sequelize.readthedocs.org/en/latest/docs/migrations/ of course. But the basic answer is you have to add everything in yourself to specify the fields you need. It doesn't do it for you.

提交回复
热议问题