I'm trying to seed data into a database and I'm getting this error:
name: 'SequelizeDatabaseError',
parent: Error: Column 'id' cannot be null
code: 'ER_BAD_NULL_ERROR',
errno: 1048,
sqlState: '23000',
sqlMessage: "Column 'id' cannot be null"
Here is the index to seed the data:
const seedUsers = require('./user-seeds');
const seedPosts = require('./post-seeds');
const seedComments = require('./comment-seeds');
const seedVotes = require('./vote-seeds');
const sequelize = require('../config/connection');
const seedAll = async () => {
await sequelize.sync({ force: true });
console.log('--------------');
await seedUsers();
console.log('--------------');
await seedPosts();
console.log('--------------');
await seedComments();
console.log('--------------');
await seedVotes();
console.log('--------------');
process.exit(0);
};
seedAll().catch(err => console.log('seedAll error: ', err));
the error seems to be thrown when seedPost() is called, the following is the corresponding model:
const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/connection');
// create Post Model
class Post extends Model {
static upvote(body, models) {
return models.Vote.create({
user_id: body.user_id,
post_id: body,post_id
}).then(() => {
return Post.findOne({
where: {
id: body.post_id
},
attributes: [
'id',
'post_url',
'title',
'created_at',
[sequelize.literal('(SELECT COUNT(*) FROM vote WHERE post.id = vote.post_id)'), 'vote_count']
],
include: [
{
model: models.Comment,
attributes: ['id', 'comment_text', 'post_id', 'user_id', 'created_at'],
include: {
model: models.User,
attributes: ['username']
}
}
]
});
});
}
}
// create field/column for Post model
Post.init(
{
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoincrement: true
},
title: {
type: DataTypes.STRING,
allowNull: false
},
post_url: {
type: DataTypes.STRING,
allowNull: false,
validate: {
isURL: true
}
},
user_id: {
type: DataTypes.INTEGER,
references: {
model: 'user',
key: 'id'
}
}
},
{
sequelize,
freezeTableName: true,
underscored: true,
modelName: 'post'
}
);
module.exports = Post;
this is what my seed file looks like:
const { Post } = require('../models');
const postdata = [
{
title: 'Donec posuere metus vitae ipsum.',
post_url: 'https://buzzfeed.com/in/imperdiet/et/commodo/vulputate.png',
user_id: 10
},
{
// ... more seeds
}
];
const seedPosts = () => Post.bulkCreate(postdata);
module.exports = seedPosts;
I'm not sure what I'm doing wrong, any help is greatly appreciated!
CodePudding user response:
// create field/column for Post model
Post.init(
{
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoincrement: true
},
In your Post.init, autoincrement
must be autoIncrement
. Maybe in your case you'll need to recreate the table