'Validation error when seeding in Sequelize
I try to seed in Sequelize with huge of data but I got an error "Validation error" when seeding. Please see my code in below.
"use strict";
const faker = require("faker");
const User = require("../models").User;
module.exports = {
up: async (queryInterface, Sequelize) => {
let products = [];
let amount = 100;
// 50 users
let users = await User.findAll();
let userCodes = users.map(user => user.code);
// output ['x312scAD', 'F32SDcvrW', ...]
function randomBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// image collections from Unsplash.com
let imagesCollection = [1163637, 190727, 6780963, 1198107, 762960, 1353633, 3321491, 217461, 2203755];
let imageWidth = 980;
let imageHeight = 555;
var uniqueNumbers = [];
while (uniqueNumbers.length < amount) {
var r = Math.floor(Math.random() * 1000) + 1;
if (uniqueNumbers.indexOf(r) === -1) uniqueNumbers.push(r);
}
while (amount--) {
let randomCollection = randomBetween(0, imagesCollection.length - 1);
let randomThumbnail = `https://source.unsplash.com/collection/${imagesCollection[randomCollection]}/${imageWidth}x${imageHeight}/?sig=${uniqueNumbers[amount]}`;
products.push({
code: 'abc' + faker.random.number(),
userCode: userCodes[randomBetween(1, userCodes.length-1)],
title: faker.lorem.sentence(),
subtitle: faker.lorem.sentence(),
description: faker.lorem.paragraphs(),
categoryId: randomBetween(1, 10),
thumbnail: randomThumbnail,
createdAt: new Date(),
updatedAt: new Date()
});
}
return await queryInterface.bulkInsert("products", products, {});
}
};
PS: User hasMany Products
I think this cause is Async/await but I am new to this kind. Please let's me know where is my fault in this case.
Can anyone help me to seeding in correct way?
Here is my product rules in models.Product
code: DataTypes.STRING(12),
userCode: DataTypes.STRING,
title: DataTypes.STRING,
subtitle: DataTypes.STRING,
description: DataTypes.TEXT,
categoryId: DataTypes.INTEGER,
thumbnail: DataTypes.STRING,
createdAt: DataTypes.Date,
updatedAt: DataTypes.Date
PS: I able to seed sometimes
Solution 1:[1]
My mistake was that I violated the unique email validation in my dummy data, once I changed it generated the seeds normally.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jood |
