I'm trying to create my initial migration to populate the test database but I can't get it working. This is what I have in my migration:
'use strict'; module.exports = { up: function (queryInterface, Sequelize) { return [ queryInterface.bulkInsert('Users', [ { username: "user1" }, { username: "user2" } ])]; }, down: function (queryInterface, Sequelize) { return queryInterface.dropTable('Users'); } };
And I get this error:
== 20151024144833-create-conjugation: migrating ======= { [SequelizeUniqueConstraintError: Validation error] name: 'SequelizeUniqueConstraintError', message: 'Validation error', errors: [], fields: [] }
There must be an easier way to do this. I've checked other SO questions, but the syntax has changed in the current version of sequelize.
UPDATE
Ok, I realized my mistake: I was assuming that sequelize would take care of the timestamps. This fixes the problem:
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() } ]) ]; }
But I'm still wondering if this is the right way to seed my database. Is there a way to do it using User.create({})
?
It has a useful command called seed:create , which will generate 2 files for you: a seed . Running this command will result in a file in your seeders directory with code that looks like this: 'use strict'; module. exports = { up: function (queryInterface, Sequelize) { /* Add altering commands here.
To insert new rows into your SQL table, you need to first create a Sequelize Model object. In Sequelize, a Model is an object that represents your SQL table, giving information to Sequelize about the name, the columns, and their data types.
When you create a Sequelize model, you can add the default value for your model by adding the defaultValue option to the column(s) definition. The defaultValue option will be used by Sequelize to define default value(s) for your SQL column(s) when you create a table using Sequelize.
You can use next:
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 }); });
Or read about "migrations" at http://docs.sequelizejs.com/en/latest/docs/migrations/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With