Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert initial data using sequelize migrations/seeds?

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({})?

like image 758
nachocab Avatar asked Oct 24 '15 21:10

nachocab


People also ask

How do you seed in Sequelize?

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.

How do I add data using Sequelize?

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.

How do I set default value in Sequelize migration?

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.


1 Answers

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/

like image 165
Eduardo Cuomo Avatar answered Sep 23 '22 20:09

Eduardo Cuomo