Node Sequelize 迁移/模型是否可以共享相同的代码? [英] Node Sequelize migrations/models is it possible to share the same code?

查看:35
本文介绍了Node Sequelize 迁移/模型是否可以共享相同的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Sequelize 的新手,所以请耐心等待.

I'm new at Sequelize so be patient.

我使用 Sequelize 启动了一个新项目和迁移,所以我有这样的:

I started up a new project using Sequelize and migrations so I've got like this:

"use strict";
module.exports = {
  up: function(migration, DataTypes, done) {
    migration.createTable("MyUsers", {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: DataTypes.INTEGER
      },
      first_name: {
        type: DataTypes.STRING
      },
      last_name: {
        type: DataTypes.STRING
      },
      bio: {
        type: DataTypes.TEXT
      },
      createdAt: {
        allowNull: false,
        type: DataTypes.DATE
      },
      updatedAt: {
        allowNull: false,
        type: DataTypes.DATE
      }
    }).done(done);
  },
  down: function(migration, DataTypes, done) {
    migration.dropTable("MyUsers").done(done);
  }
};

模型/myuser.js:

"use strict";
module.exports = function(sequelize, DataTypes) {
  var MyUser = sequelize.define("MyUser", {
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    bio: DataTypes.TEXT
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
      }
    }
  });
  return MyUser;
};

如你所见表定义是关于迁移和模型文件.

as you can see the table definition is both on the migration and the model file.

我想知道有没有分享的方法代码?

I'm wondering if there is a way to share the code ?

我的意思是我不喜欢在两个文件中有逻辑如果字段更改,我必须更新两次.

I mean I don't like to have logic in two files if a field change I've to update twice.

按照下面的Yan Foto示例不同的方式可能更干净.

following the Yan Foto example below a different way may be cleaner.

'use strict';

module.exports = {
    name: 'users',
    definition : function(DataTypes)  {
        return {
            id: {
                type: DataTypes.INTEGER,
                autoIncrement: true,
                primaryKey: true
            },
            firstname: {
                type:DataTypes.STRING
            },
            lastname: {
                type:DataTypes.STRING
            },
            email: {
                type: DataTypes.STRING,
                unique: true
            },
            username: {
                type:DataTypes.STRING,
                unique: true
            }
        };
    }
};

模型/用户

'use strict';

var Schema = require('../schemas/users');

module.exports = function(sequelize, DataTypes) {
    return sequelize.define(
        Schema.name,
        Schema.definition(DataTypes),
        {
            freezeTableName: true ,
                instanceMethods: {
                countTasks: function() {
                        // how to implement this method ?
                }
                }
        }
    );
};

迁移/20150720184716-users.js

'use strict';

    var Schema = require('../schemas/users');

    module.exports = {

        up: function (queryInterface, Sequelize) {
                return queryInterface.createTable(
                Schema.name,
                Schema.definition(Sequelize)
                );
        },

        down: function (queryInterface, Sequelize) {
            return queryInterface.dropTable(Schema.name);
        }

    };

推荐答案

当我开始使用 sequelize 时,我想知道同样的事情,这里是我的解决方案.我将我的模型定义如下:

I wondered the same thing as I started using sequelize and here is my solution. I define my models as bellow:

module.exports = {
  def: function(DataTypes) {
    return {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
      },
      username: DataTypes.STRING,
      password: DataTypes.STRING,
      createdAt: DataTypes.DATE,
      updatedAt: DataTypes.DATE,
    }
  },
  config: {}
};

其中 def 定义属性,configdefine迁移方法.我使用以下代码导入它们:

Where def defines the attributes and config is the optional options object accepted by define or migration methods. And I import them using the following code:

fs.readdirSync(__dirname + '/PATH/TO/models')
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename);
  })
  .forEach(function(file) {
    var name = file.substring(0, file.lastIndexOf(".")),
        definition = require(path.join(__dirname + '/models', file));

    sequelize['import'](name, function(sequelize, DataTypes) {
      return sequelize.define(
        name,
        definition.def(DataTypes),
        definition.config
      );
    });
  });

对于迁移,我有类似的方法:

For the migrations I have a similar approach:

const path = require('path');

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.createTable(
      'users',
      require(path.join(__dirname + '/PATH/TO/models', 'user.js')).def(Sequelize)
    );
  },

  down: function (queryInterface, Sequelize) {
    return queryInterface.dropTable('users');
  }
};

这篇关于Node Sequelize 迁移/模型是否可以共享相同的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆