Column Cannot be NULL even if value is defined - javascript

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!

// 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

Related

Column specified twice error in sequelize

I have defined two table with many-to-many association between them.
create-image-migration.js
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Images', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
...
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Images');
}
};
create-category-migration.js
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Categories', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
...
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Categories');
}
};
Now JOIN table is defined as follows
create-image-category-migration.js
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('ImageCategories', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
imageId: {
type: Sequelize.INTEGER,
allowNull: false,
references: { model: 'Images', key: 'id' }
},
categoryId: {
type: Sequelize.INTEGER,
allowNull: false,
references: { model: 'Categories', key: 'id' }
},
...
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('ImageCategories');
}
};
image-category-model.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const ImageCategory = sequelize.define('ImageCategory', {
imageId: {
type: DataTypes.INTEGER,
allowNull: false,
references: { model: 'Image', key: 'id' },
},
categoryId: {
type: DataTypes.INTEGER,
allowNull: false,
references: { model: 'Category', key: 'id' },
},
...
}, {});
ImageCategory.associate = function(models) {
models.Image.belongsToMany(models.Category, { through: ImageCategory });
models.Category.belongsToMany(models.Image, { through: ImageCategory });
};
return ImageCategory;
};
Now when I run the migration the join table is created with respective column name as specified in migration file i.e. in camel case.
But when I run the following bulkCreate command in sequelize to insert data
await db.ImageCategory.bulkCreate([
{ imageId: 'someId', categoryId: topicId, categoryType: 'topic' },
{ imageId: 'someId', categoryId: styleId, categoryType: 'style' },
]);
I am get the following error:
sqlMessage: "Column 'imageId' specified twice",
sql: "INSERT INTO `ImageCategories` (`imageId`,`categoryId`,`categoryType`,`createdAt`,`updatedAt`,`ImageId`) VALUES (5,'22','topic','2022-11-26 08:11:41','2022-11-26 08:11:41',NULL),(5,'27','style','2022-11-26 08:11:41','2022-11-26 08:11:41',NULL);"
},
As we can see here "ImageId" is automatically added by sequelize. So my question is if there is a convention followed by sequelize to name the column name while creating join table since it is not mention anywhere on its documentation.
By default Sequelize generates foreign key names in the pascal case. You do have foreign keys in the junction table that differ with the letter case.
So you just need to indicate foreign keys explicitly in both associations:
ImageCategory.associate = function(models) {
models.Image.belongsToMany(models.Category, { through: ImageCategory, foreignKey: 'imageId' });
models.Category.belongsToMany(models.Image, { through: ImageCategory, foreignKey: 'categoryId' });
};

Generated table using belongstomany is not associated with any table

I have three tables companies, subscriptions and companySubscription. As name defined company can canbuy/have plan or one subscription belongs to many companies.
So in model/schema I have defined as follows:
companies.js
const sequelize = require("../utils/database");
const bcrypt = require("bcrypt");
const { DataTypes, Model } = require("sequelize");
const subscription = require("./subscriptions");
const CompanySubscription = require("./companySubscription");
class companies extends Model {}
companies.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
contactNo: {
type: DataTypes.STRING,
allowNull: true,
},
companySize: {
type: DataTypes.INTEGER,
allowNull: true,
},
},
{ sequelize, modelName: "companies" }
);
subscription.belongsToMany(companies, { through: CompanySubscription });
module.exports = companies;
subscription.js
const sequelize = require("../utils/database");
const { DataTypes, Model } = require("sequelize");
class subscription extends Model {}
subscription.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
subscriptionPlanType: {
type: DataTypes.ENUM,
values: ["Yearly", "Monthly"],
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},
memberCount: {
type: DataTypes.INTEGER,
allowNull: false,
},
amount: {
type: DataTypes.FLOAT,
allowNull: false,
},
},
{ sequelize, modelName: "subscription" }
);
module.exports = subscription;
companySubscription.js
const sequelize = require("../utils/database");
const companies = require("./companies");
const subscription = require("./subscriptions");
const { DataTypes, Model } = require("sequelize");
class CompanySubscription extends Model {}
CompanySubscription.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
status: {
type: DataTypes.ENUM,
values: ["active", "inactive"],
},
subscriptionType: {
type: DataTypes.ENUM,
values: ["Yearly", "Monthly"],
},
subscriptionPlanStartDate: {
type: DataTypes.DATE,
},
subscriptionPlanEndDate: {
type: DataTypes.DATE,
},
paidStatus: {
type: DataTypes.ENUM,
values: ["paid", "unpaid"],
},
paidDate: {
type: DataTypes.DATE,
},
},
{ sequelize, modelName: "CompanySubscription" }
);
module.exports = CompanySubscription;
In controller file I am able to manage to insert the data. Below is the code:
const addBIlling = async (req, res) => {
const foundSubcscription = await subscription.create({
subscriptionPlanType: "Monthly",
name: "s1",
memberCount: 15,
amount: 50.55,
});
const foundCompany = await companies.create({
name: "company1",
email: "company1#gmail.com",
contactNo: "87964644",
companySize: 20,
});
const insertedData = await foundSubcscription.addCompany(foundCompany, {
through: {
status: "active",
paidStatus: "paid",
subscriptionType: "Monthly",
subscriptionPlanEndDate: moment().add(1, "months"),
paidDate: moment().add(1, "months"),
},
});
console.log("inserted data ", insertedData);
res.json({ data: insertedData });
};
Now I want to fetch the records from db as which company has bought which subscription plan!
i.e. company name, subscription plan and its active and paid status and plan's expiry date.
I tried below code:
const billingList = async (req, res) => {
const billingData = await CompanySubscription.findAll({
include: [{ model: companies }],
});
console.log("billing data ", billingData);
};
Above code is throwing error "companies is not associated to CompanySubscription!".
Where have I made a mistake?
Don't try to import models to each other's modules directly. Define model registration functions in each model module and use them all to register models in one place/module and for associations you can define associate function inside each registration function and call them after ALL your models are already registered. That way you won't have cyclic dependencies and all associations will be correct.
See my answer here to get an idea how to do it.

Sequelize: A is not associated to B" nodejs

I have two models in which one is Question and other is Answer, each answer has one question_id and question can have more then one answers.
I want to include all the answers of each question in my json response but I am keep getting an error
"message": "answer is not associated to question!"*
Below is the Question model:-
module.exports = (sequelize, Sequelize) => {
const Question = sequelize.define("question", {
question_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
question_no: {
type: Sequelize.DOUBLE,
allowNull: false
},
question_text: {
type: Sequelize.STRING,
allowNull: false
},
question_text: {
type: Sequelize.STRING,
allowNull: false
},
question_required: {
type: Sequelize.BOOLEAN,
},
formpage_no: {
type: Sequelize.DOUBLE,
allowNull: false
},
med_id: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'medforms',
key: 'med_id'
},
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
},
med_name: {
type: Sequelize.STRING,
allowNull: true
},
version_no: {
type: Sequelize.STRING,
allowNull: false
}
}, {
freezeTableName: false, // true: if we want to make table name as we want else sequelize will make them prural
underscored: true // underscored: true indicates the the column names of the database tables are snake_case rather than camelCase
});
Question.associate = function (models) {
Question.hasMany(models.answer, {
foreignKey: 'question_id',
as: 'answers'
});
Question.hasMany(models.helpbox, {
foreignKey: 'question_id',
as: 'helpboxes'
});
// in future each question could have more than one document text
};
return Question;
};
And below is my answer model:-
module.exports = (sequelize, Sequelize) => {
const Answer = sequelize.define("answer", {
answer_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
question_id: { // each answer has one questionId
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'questions',
key: 'question_id'
},
onUpdate: 'CASCADE',
onDelete: 'CASCADE',
},
question_no: {
type: Sequelize.DOUBLE,
allowNull: true
},
answer_no: {
type: Sequelize.DOUBLE,
allowNull: true
},
answer_text: {
type: Sequelize.STRING,
allowNull: false
},
answer_icon: {
type: Sequelize.STRING,
allowNull: true
},
answer_reply: {
type: Sequelize.STRING,
allowNull: true
},
answer_logic: {
type: Sequelize.STRING,
allowNull: true
},
med_name: {
type: Sequelize.STRING,
allowNull: true
},
version_no: {
type: Sequelize.STRING,
allowNull: false
},
}, {
freezeTableName: false, // true: if we want to make table name as we want else sequelize will make them prural
underscored: true // underscored: true indicates the the column names of the database tables are snake_case rather than camelCase
});
Answer.associate = function (models) {
Answer.belongsTo(models.question, {
as: 'questions'
});
// in future each question could have more than one document text
};
return Answer;
};
below is the index.js class:-
var Sequelize = require('sequelize');
var env = process.env.NODE_ENV || 'development';
var config = require("../config/config.json")[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
db.Sequelize = Sequelize;
db.sequelize = sequelize;
// Models
db.medform = require("./medform.model.js")(sequelize, Sequelize);
db.version = require("./version.model.js")(sequelize, Sequelize);
db.question = require("./question.model.js")(sequelize, Sequelize);
db.helpbox = require("./helpbox.model.js")(sequelize, Sequelize);
db.answer = require("./answer.model.js")(sequelize, Sequelize);
db.document = require("./document.model.js")(sequelize, Sequelize);
module.exports = db;
This is my question controller
// Retrieve Question including answers from the database:
exports.getAllQuesData = (req, res) => {
const version_no = req.query.version_no;
const med_id = req.query.med_id;
var condition = [{ "version_no": version_no }, { "med_id": med_id }];
Question.findAll({
include: [
{
model: answer,
as: 'answers'
}
],
where: condition
})
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving questions."
});
});
};
Please help me what I am doing wrong why my associations are not working
You didn't register model associations. See my answer how to do it
Object.keys(db).forEach(function (modelName) {
if (db[modelName].associate) {
db[modelName].associate(db)
}
})

Associate in Sequelize not working as intended

I am trying to associate two tables in Sequelize but I am getting the SequelizeEagerLoadingError that one table is not associated to another despite trying all the available fixes on this platform.
I have two tables, User and Item.
User (user.js)
const User = dbconnection.sequelize.define('users', {
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true},
name: {
type: Sequelize.STRING(80),
allowNull: false
},
email: {
type: Sequelize.STRING(120),
allowNull: false,
unique: true
},
dob: {
type: Sequelize.DATEONLY,
allowNull: false
},
password: {
type: Sequelize.STRING(256),
allowNull: false
}
});
User.associate = models => {
User.hasMany(models.Item, { as: 'items',foreignKey: 'user_id' })
}
dbconnection.sequelize.sync({ force: false })
.then(() => {
//console.log('Table created!')
});
module.exports = {
User
};
Item (item.js)
const Item = dbconnection.sequelize.define('items', {
id: { type: Sequelize.INTEGER, unique: true, autoIncrement: true, primaryKey: true},
item: {
type: Sequelize.STRING(80),
allowNull: true
},
item_type: {
type: Sequelize.STRING(10),
allowNull: false
},
comment: {
type: Sequelize.STRING(1000),
allowNull: true
},
user_id: {
type: Sequelize.INTEGER,
allowNull: false,
references: { model: 'users', key: 'id' }
},
});
Item.associate = models => {
Item.belongsTo(models.User, { as: 'users',foreignKey: 'user_id' })
}
dbconnection.sequelize.sync({ force: false })
.then(() => {
// console.log('Table created!')
})
});
module.exports = {
Item
};
User hasMany(Item) while Item belongsTo(User) as shown above.
However, when I make a query to the Item table (as below),
const usersdb = require('./userdb')
const itemsdb = require('./itemdb')
class ItemsController {
static async getAllItems(req, res, next) {
try{
let allitems = await itemsdb.Item.findAll({
include: [{
model: usersdb.User
}]
})
return {items: allitems, status: true}
}
catch (e) {
return {items: e, status: false}
}
}
}
module.exports = ItemsController;
I get the SequelizeEagerLoadingError that "users is not associated to items!"
I have tried all the available fixes including this and this among others but to no success.
I have finally found a workaround. First, I dropped the tables and discarded the model definitions. Second, I generated migrations and models using the sequelize model:create --name ModelName --attributes columnName:columnType command. I then used the generated models to associate the two tables just as I had done earlier. Lastly, I ran the sequelize db:migrate command to create the tables and on running the query, it worked!
Earlier, I was creating the models manually. I was also creating the tables using the sequelize.sync({force: false/true}) command after loading the models.
User Model (user.js)
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
email: {
type: DataTypes(120),
allowNull: false,
unique: true
},
dob: {
type: DataTypes.DATEONLY,
allowNull: false
},
password: {
type: DataTypes.STRING(256),
allowNull: false
}
}, {});
User.associate = function(models) {
User.hasMany(models.Item, {as: 'Item', foreignKey: 'user_id'})
};
return User;
};
Item model (item.js)
'use strict';
module.exports = (sequelize, DataTypes) => {
const Item = sequelize.define('Item', {
item: {
type: DataTypes.STRING(80),
allowNull: true
},
item_type: {
type: DataTypes.STRING(10),
allowNull: false
},
comment: {
type: DataTypes.STRING(1000),
allowNull: true
},
user_id: {
type: DataTypes.INTEGER,
allowNull: false,
references: { model: 'User', key: 'id' }
}
}, {});
Item.associate = function(models) {
Item.belongsTo(models.User, { as: 'User',foreignKey: 'user_id' })
};
return Item;
};
Query (queryitem.js)
const Item = require('../models').Item
const User = require('../models').User
class ItemsController {
static async getAllItems() {
try{
let allitems = await Item.findAll({
include: [{
model: User,
as: 'User'
}]
})
return {items: allitems, status: true}
}
catch (e) {
return {items: e, status: false}
}
}
}
module.exports = ItemsController;

Sequelize association include returns null

I am having an issue when I'm trying to associate a table into my query with sequelize-cli.
My query works but it doesn't populate Adresse table. Only Patient is populated. Adresse array is ignored. (return null)
I made a one-to-one relationship between the tables and am not sure if that's the cause of the error or if it is somewhere else where I am associating the two tables.
here is my models :
server/models/patient.js
module.exports = (sequelize, Sequelize) => {
const Patient = sequelize.define('Patient', {
///
}, {
classMethods: {
associate: (models) => {
Patient.belongsTo(models.Adresse, {
foreignKey: 'adresseId',
});
}
}
});
return Patient;
};
server/models/adresse.js
module.exports = function(sequelize, Sequelize) {
const Adresse = sequelize.define('Adresse', {
adresse: {
type: Sequelize.STRING,
allowNull: false,
},
complementAdr: {
type: Sequelize.STRING
},
codePostal: {
type: Sequelize.INTEGER,
allowNull: false
},
}, {
classMethods: {
associate: (models) => {
Adresse.hasMany(models.Patient, {
foreignKey: 'adresseId',
as: 'Patients',
});
}
}
});
return Adresse;
};
and here is where I specified the association on my migration files :
server/migrations/20170326145609-create-patient.js
adresseId: {
type: Sequelize.INTEGER,
references: {
model: 'Adresses',
key: 'id_adresse',
as: 'adresseId',
},
},
server/migrations/20170326145502-create-adresse.js
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Adresses', {
id_adresse: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
adresse: {
type: Sequelize.STRING,
allowNull: false,
},
complementAdr: {
type: Sequelize.STRING
},
codePostal: {
type: Sequelize.INTEGER,
allowNull: false
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Adresses');
}
};
and finally here is my query on my controller file :
server/controllers/patients.js
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const Patient = require('../models').Patient;
const Adresse = require('../models').Adresse;
module.exports = {
create(req, res) {
return Patient
.create({
///
adressesId: {
adresse: req.body.adresse,
codePostal: req.body.codePostal,
}
}, {
include: [{
model : Adresse
}]
})
.then(patient => res.status(201).send(patient))
.catch(error => res.status(400).send(error));
}
};
Try using Adresse instead adresseId when eager creating the Adresse model instance related to given Patient
return Patient.create({
// patient attributes,
Adresse: {
adresse: req.body.adresse,
codePostal: req.body.codePostal
},
include: [ Adresse ]
}).then(patient => {
// look at the query generated by this function
// it should create both patient and adresse
});

Categories