为什么我"UnhandledPromiseRejectionWarning: Error at Query.run"尝试实现与 sequelize、mysql 和 Nodejs 的一对多关系?



我正在尝试使用sequelize, MySQL和Node-Express建立一对多关系,我得到以下错误。

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.

这是MY Model/index.js中发生关系的地方

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'
})

模型/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
}
})
}

评估模型

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

产品控制器
//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
}

如果我从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'
})

一切运行顺利,所以我确信错误来自我试图实现的关系,我通过文档尝试实现它不同,但我仍然得到相同的错误。

在你的代码中,你调用返回Promise的sync(..)方法。看来这个承诺被拒绝了。所以试着替换

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

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

最新更新