如何使用sequelize migrations / seeds插入初始数据?

时间:2015-10-24 21:43:28

标签: node.js express migration sequelize.js

我尝试创建初始迁移以填充测试数据库,但我无法使其正常运行。这就是我在迁移中所拥有的:

'use strict';

module.exports = {
  up: function (queryInterface, Sequelize) {
    return [
      queryInterface.bulkInsert('Users', [
        { username: "user1" },
        { username: "user2" }
    ])];
  },

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

我收到了这个错误:

== 20151024144833-create-conjugation: migrating =======
{ [SequelizeUniqueConstraintError: Validation error]
  name: 'SequelizeUniqueConstraintError',
  message: 'Validation error',
  errors: [],
  fields: [] }

必须有一种更简单的方法来做到这一点。我已经检查了其他SO问题,但是在当前版本的sequelize中语法已经改变了。

更新

好吧,我意识到自己的错误:我假设sequelize会处理时间戳。这解决了这个问题:

up: function (queryInterface, Sequelize) {
  console.log(User);
  return [
    queryInterface.bulkInsert('Users', [
      { username: "user1", createdAt: Date.now(), updatedAt: Date.now() },
      { username: "user2", createdAt: Date.now(), updatedAt: Date.now() }
    ])
  ];
}

但我仍然想知道这是否是种子数据库的正确方法。有没有办法使用User.create({})

4 个答案:

答案 0 :(得分:4)

可以使用替代方法:sequelize fixtures,您可以使用声明为json文件或其他格式的默认数据来初始化表。

答案 1 :(得分:2)

您可以使用下一个:

const City = sequelize.define('city', {
  name: { type: Sequelize.STRING },
  order_: { type: Sequelize.INTEGER }
});
City.sync().then(() => {
  City.create({
    name: 'Neuquen',
    order_: 0
  });
  City.create({
    name: 'General Roca',
    order_: 1
  });
});

或阅读"迁移"在http://docs.sequelizejs.com/en/latest/docs/migrations/

答案 2 :(得分:2)

new Date()

也需要mysql,即

  return queryInterface.bulkInsert('users', [
  {
    "Forename":"A",
    "Surname": "User",
    "UserType":"1",
    "Email":"auser@gmail.com",
    "Password":"password",
    "LastLogin":0,
    "Tokens": JSON.stringify({"tokens":[]}),
    "CreatedBy": 999,
    "CreatedAt": new Date(),
    "UpdatedAt": new Date()
  }]);

答案 3 :(得分:0)

对于 sequelize v6 的快速简便方法(无种子或迁移):

我修改了我的 sequelize.sync() 调用:

import { Sequelize } from 'sequelize';

// This will create an in-memory sqlite db
const sequelize = new Sequelize('sqlite::memory:', {
  logging: sequelizeLogger
});

await sequelize
  .sync({ force: true })
  .then(() => {
    // seed db
    Users.create({ username: 'user1' })
  });