Home > front end >  Sequelize Bad Field Error on Eager loading after changing association
Sequelize Bad Field Error on Eager loading after changing association

Time:02-14

// Include Sequelize module. 
const Sequelize = require('sequelize') 
  
// Import sequelize object,  
// Database connection pool managed by Sequelize. 
const sequelize = require('./database.js') 

const User = require('./User.js');
const Product = require('./Product.js');
  
// Define method takes two arrguments 
// 1st - name of table 
// 2nd - columns inside the table 
const FavoriteProduct = sequelize.define('favorite_product', { 

    favorite_id:{ 
  
        // Sequelize module has INTEGER Data_Type. 
        type:Sequelize.INTEGER, 
  
        autoIncrement:true, 

        allowNull:false, 
  
        primaryKey:true
    }, 

    createdAt: Sequelize.DATE,

    //no dates

}, {
    updatedAt: false
}); 

User.hasMany(FavoriteProduct, { foreignKey: 'user_id'} );
Product.hasMany(FavoriteProduct, { foreignKey: 'product_id'} );

FavoriteProduct.belongsTo(Product, { foreignKey: 'product_id'});
FavoriteProduct.belongsTo(User, { foriegnKey: 'user_id'})

module.exports = FavoriteProduct

Previously I had this model as a BelongsToMany model, with both Product and User->belongToMany through FavoriteProduct. I changed it because the eager loading of FavoriteProduct was not working when trying to load from products. I now have a new issue, attempting to eager load the new table throws this error:

    "code": "ER_BAD_FIELD_ERROR",
    "errno": 1054,
    "sqlState": "42S22",
    "sqlMessage": "Unknown column 'favorite_product.userUserId' in 'field list'",

I don't know why this occurred, but it must be because I attempted to switch from a belongsToMany association without doing any migrations. There are no extra columns in the database or anything like that.

Does anyone know how to fix this field issue without deleting the table?

For reference, I am simply doing this:

await Product.findOne({
        include: [{
            model: FavoriteProduct,
            required: false,
        }]

CodePudding user response:

You need to correct the association FavoriteProduct.belongsTo(User: you misspelt the option foreignKey by indicating foriegnKey.

FavoriteProduct.belongsTo(User, { foreignKey: 'user_id'})
  • Related