我最近开始使用Sequelize来获取我的postgresql数据库的模型。为了映射数据库,我使用了sequelize-auto。当我以这种方式将参数发送到数据库的构造函数时,我可以使用sequelize-auto创建数据库的自动生成映射:
init.js
let sequelizeAutoInstance = new SequelizeAuto(dbName,username,password,options)但当我尝试以这种方式发送Sequelize实例时,它不起作用:
new-init.js
let sequelizeInstance = new Sequelize(sequelizeOptions);
sequelizeAutoInstance = new SequelizeAuto(sequelizeInstance)查看sequelize-auto ctor,我看到它运行以下代码行:
if (database instanceof Sequelize) {
this.sequelize = database;
}但是从new Sequelize返回的实例没有返回Sequelize的实例。
我错过了什么?谢谢
发布于 2020-05-20 15:37:37
如果我没记错的话。您需要将sequelize的实例传递给您的模型。如果您使用的是扩展模型,则只需将实例传入init选项即可。
const { Sequelize, DataTypes, Model } = require('sequelize');
const sequelize = require("../your/db/file");
class User extends Model {}
User.init({
// Model attributes are defined here
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
// allowNull defaults to true
}
}, {
// Other model options go here
sequelize, // We need to pass the connection instance
modelName: 'User' // We need to choose the model name
});
如果它正常工作,那么
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = require("../your/db/file");
const User = sequelize.define('User', {
// Model attributes are defined here
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
// allowNull defaults to true
}
}, {
// Other model options go here
});
所有这些都可以在Sequelize models文档中找到
https://stackoverflow.com/questions/53078640
复制相似问题