Home > Back-end >  Why am I getting "UnhandledPromiseRejectionWarning: Error at Query.run" trying to implemen
Why am I getting "UnhandledPromiseRejectionWarning: Error at Query.run" trying to implemen

Time:11-15

I am trying to establish One-to-many relation using sequelize, MySQL and Node-Express I am getting the following error.

server is running on port : 8080
Executing (default): SELECT 1 1 AS result
Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'products' AND TABLE_SCHEMA = 'node_sequelize_api_db'
connected to db
Executing (default): CREATE TABLE IF NOT EXISTS `products` (`id` INTEGER NOT NULL auto_increment , `title` VARCHAR(255) NOT NULL, `price` INTEGER, `description` TEXT, `published` TINYINT(1), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `products`
Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'reviews' AND TABLE_SCHEMA = 'node_sequelize_api_db'
Executing (default): CREATE TABLE IF NOT EXISTS `reviews` (`id` INTEGER NOT NULL auto_increment , `rating` INTEGER, `description` TEXT, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `productId` INTEGER, PRIMARY KEY (`id`), FOREIGN KEY (`productId`) REFERENCES `products` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) ENGINE=InnoDB;
(node:15924) UnhandledPromiseRejectionWarning: Error
    at Query.run (/home/grace/Desktop/_SOFTWARE_ENGINEER/FULLSTACK/node_sequelize/node_modules/sequelize/lib/dialects/mysql/query.js:52:25)
    at retry (/home/grace/Desktop/_SOFTWARE_ENGINEER/FULLSTACK/node_sequelize/node_modules/sequelize/lib/sequelize.js:314:28)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:15924) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:15924) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

THIS IS MY Model/index.js where the relation happens

require('dotenv').config();
const {Sequelize, DataTypes} = require('sequelize')

const sequelize = new Sequelize(
    process.env.DB,
    process.env.USER,
    process.env.PASSWORD,{
        host:process.env.HOST,
        dialect: process.env.DIALECT,
        operatorsAlias: false,
        /*pool:{
            max: dbConfig.pool.max,
            min: dbConfig.pool.min,
            acquire: dbConfig.pool.acquire,
            idle: dbConfig.pool.idle
        }*/
    }
)

sequelize.authenticate()
.then(() =>{
    console.log('connected to db')
})
.catch(err =>{
    console.log('Error'   err)
})

const db = {}
db.Sequelize = Sequelize
db.sequelize = sequelize

db.products = require('./productModel.js')(sequelize, DataTypes);
db.reviews = require('./reviewModel.js')(sequelize, DataTypes);

//it won't create the table over and over
db.sequelize.sync({force: false})
.then(()=>{
    console.log('yes re-sync done!')
})

//implement One-to-Many relationship

db.products.hasMany(db.reviews,{
    foreignKey: 'product_id',
    as: 'review',
})

db.reviews.belongsTo(db.products,{
    foreignKey: 'product_id',
    as: 'product'
})

Model/productModel.js

module.exports = (sequelize, DataTypes) => {
    return sequelize.define("product", {
        title: {
            type: DataTypes.STRING,
            allowNull: false
        },
        price: {
            type: DataTypes.INTEGER
        },
        description: {
            type: DataTypes.TEXT
        },
        published: {
            type: DataTypes.BOOLEAN
        }
    })
}

Review Model

module.exports = (sequelize, DataTypes) => {
    return sequelize.define("review", {
        rating: {
            type: DataTypes.INTEGER,
        },
        description: {
            type: DataTypes.TEXT
        }
    })
}

Product controller

//7. connect 1 to many relation Roduct to Review
const getProductReviews = async (req, res) =>{
    try{
        const data = await Product.findAll({include: Review})
    }catch(e){
        console.error(e)
    }
}


module.exports ={
    addProduct,
    getAllProducts,
    getOneProduct,
    updateProduct,
    deleteProduct,
    getPublishedProduct,
    getProductReviews
}

If I remove the following code from Model/index.js

//implement One-to-Many relationship

db.products.hasMany(db.reviews,{
    foreignKey: 'product_id',
    as: 'review',
})

db.reviews.belongsTo(db.products,{
    foreignKey: 'product_id',
    as: 'product'
})

Everything runs smoothly, so I am convinced that the error comes from the relationship I am trying to implement, I went through the documentation try to implement it differently but I am still getting the same error.

CodePudding user response:

In your code you call sync(..) method which returns Promise. And looks like this promise is rejected. So try to replace

db.sequelize.sync({force: false})
.then(()=>{
    console.log('yes re-sync done!')
})

with something like

db.sequelize.sync({force: false})
.then(()=>{
    console.log('yes re-sync done!')
})
.catch(e=>console.log("Can't syncronize",e));
  • Related