gpt4 book ai didi

javascript - 为什么 sequelize.sync() 不同步表,除非我将模态导入文件?

转载 作者:行者123 更新时间:2023-12-03 22:30:44 26 4
gpt4 key购买 nike

我正在将 postgres 与 sequelize 一起使用。我正在尝试在数据库中创建一个 Products 表。在主脚本文件 (app.js) 上,我调用了 sequelize.sync() 以将模态与数据库同步。但是,无论我尝试了多少次,该表都没有在数据库中制作。执行的唯一查询是这个;

Executing (default): SELECT 1+1 AS result
但是,当我将模态导入 app.js 文件时,同步发生得很好。我真的对这种行为感到困惑。
这些是我的文件;
./utils/database.js
const { Sequelize } = require("sequelize");

module.exports = new Sequelize("mydatabase", "myname", "mypassword", {
host: "localhost",
dialect: "postgres",
operatorsAliases: false,

pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000,
},
});
./modals/product.js
const { Sequelize, DataTypes } = require("sequelize");

const sequelize = require("../utils/database.js");

const Product = sequelize.define("Product", {
id: {
type: DataTypes.UUID,
defaultValue: Sequelize.UUIDV4,
allowNull: false,
primaryKey: true,
},
title: {
type: DataTypes.STRING,
},
price: {
type: DataTypes.DOUBLE,
allowNull: false,
},
imageUrl: {
type: DataTypes.STRING,
},
description: {
type: DataTypes.STRING,
},
});

// export the Modal
module.exports = Product;
./app.js
const sequelize = require("./utils/database.js");

sequelize.sync()
.then(() => {

// listen
app.listen(3000, () => {
console.log("Server running...");
});


})
.catch((error) => {
console.log(error);
});
上面的代码同步失败。但是如果我将模态导入到这个文件中,它就可以正常工作。
const sequelize = require("./utils/database.js");

// importing Product modal
const Product = require("./models/product.js");


sequelize.sync()
.then(() => {

// listen
app.listen(3000, () => {
console.log("Server running...");
});


})
.catch((error) => {
console.log(error);
});
如果要使用 sync() 函数,是否总是需要将所有模态导入 app.js 文件?

最佳答案

稍微改变你的文件结构,尝试如下
./utils/database.js

const { Sequelize } = require("sequelize");

const sequelize = new Sequelize("mydatabase", "myname", "mypassword", {
host: "localhost",
dialect: "postgres",
operatorsAliases: false,

pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000,
},
});

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;

module.exports = db;
./modals/product.js
const { DataTypes } = require("sequelize");

const db = require("../utils/database.js");

const Product = db.sequelize.define("Product", {
id: {
type: DataTypes.UUID,
defaultValue: db.Sequelize.UUIDV4,
allowNull: false,
primaryKey: true,
},
title: {
type: DataTypes.STRING,
},
price: {
type: DataTypes.DOUBLE,
allowNull: false,
},
imageUrl: {
type: DataTypes.STRING,
},
description: {
type: DataTypes.STRING,
},
});

// export the Modal
module.exports = Product;

关于javascript - 为什么 sequelize.sync() 不同步表,除非我将模态导入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67207632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com