我正在嘗試使用 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.
這是我的 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'
})
一切運行順利,所以我確信錯誤來自我試圖實作的關系,我瀏覽了檔案嘗試以不同的方式實作它,但我仍然遇到同樣的錯誤。
uj5u.com熱心網友回復:
在您的代碼中,您呼叫sync(..)回傳 Promise 的方法。看起來這個承諾被拒絕了。所以嘗試更換
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));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534420.html
