My models/index.js file:
'use strict';
const fs = require('fs');
const path = require('path');
const {Sequelize, Op, Model, DataTypes} = require("sequelize");
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
db.sequelize.define('Category', {
name: {type: String, allowNull: false},
url: {type: String, allowNull: false, unique: true},
}, {
freezeTableName: true,
timestamps: true
}
);
db.sequelize.sync({ force: true }); # it should create table
module.exports = db.sequelize.models;
console.log(db.sequelize.models) # output: {Category: Category}
If I make any queries to the model it throw an err:
UnhandledPromiseRejectionWarning: SequelizeDatabaseError: SQLITE_ERROR: no such table: Category;
How can I insert the models in db?
You need to create a migration script to create the table,
shell$ sequelize migration:create --name create-category-table
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('Categories', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Categories');
}
};
shell$ sequelize db:migrate
Related
I am new to sequelize orm.
While developing backend with express, sequelize and mssql, I created models with sequelize-cli.
Before I have index.js file and new models created by seqeulize-cli command 'sequelize init' and 'sequelize model:generate..", I had no issue.
But as I start the server I encountered the error saying "TypeError: Class constructor model cannot be invoked without 'new'".
I have not touched index.js file and the new model generated by sequelize-cli is class-basis.
I tried to change class-basis model to sequelize.define() but still get the same error.
Please help me resolve the issue.
Thanks!!
Here is my code.
index.js
"use strict";
const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const process = require("process");
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || "development";
const config = require(__dirname + "/../config/config.json")[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
sequelize = new Sequelize(
config.database,
config.username,
config.password,
config
);
} else {
}
fs.readdirSync(__dirname)
.filter((file) => {
return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
);
})
.forEach((file) => {
console.log("##########", path.join(__dirname, file))
const model = require(path.join(__dirname, file))(
sequelize,
Sequelize.DataTypes
);
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
GroupCode.js
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class GroupCode extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate({ CommonCode }) {
// define association here
this.hasMany(CommonCode);
}
}
GroupCode.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
description: {
type: DataTypes.STRING,
},
active: {
type: DataTypes.BOOLEAN,
defaultValue: true,
},
createdBy: {
type: DataTypes.STRING,
},
updatedBy: {
type: DataTypes.STRING,
},
},
{
sequelize,
modelName: "GroupCode",
}
);
return GroupCode;
};
CommonCode.js
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class CommonCode extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate({ GroupCode }) {
// define association here
this.belongsTo(GroupCode, {
foreignKey: { name: "groupCodeId", allowNull: false },
});
}
}
CommonCode.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
value: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
seq: {
type: DataTypes.INTEGER,
default: 1,
},
active: {
type: DataTypes.BOOLEAN,
defaultValue: true,
},
createdBy: {
type: DataTypes.STRING,
},
updatedBy: {
type: DataTypes.STRING,
},
},
{
sequelize,
modelName: "CommonCode",
}
);
return CommonCode;
};
Resolve the error that appears when start the server.
(Update below)
I'm trying to set up model associations using Sequelize and the .associate method.
I have the setup below but this returns an error:
UnhandledPromiseRejectionWarning: SequelizeEagerLoadingError:
ProductMember is not associated to Product!
What am I doing wrong?
Db setup:
const { Sequelize } = require("sequelize");
const config = require("./db.config.js");
const sequelize = new Sequelize(config[process.env]);
module.exports = sequelize;
db.config.js:
module.exports = {
development: {
database: DB_NAME,
username: DB_USER,
password: DB_PASS,
dialect: DB_DRIVER,
logging: false,
options: {
host: DB_HOST,
port: DB_PORT,
pool: {},
},
},
}
/models/product.js:
const { DataTypes } = require("sequelize");
const sequelize = require("../db");
const Product = sequelize.define(
"Product",
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
name: {
type: DataTypes.STRING(255),
unique: true,
allowNull: false,
},
}
{
tableName: "products",
}
}
Product.associate = (models) => {
Product.belongsToMany(models.User, {
through: models.ProductMember,
foreignKey: "product_id",
otherKey: "user_id",
});
Product.hasMany(models.ProductMember, {
foreignKey: "product_id",
allowNull: false,
});
};
module.exports = sequelize.model("Product", Product);
models/user.js:
const { DataTypes } = require("sequelize");
const sequelize = require("../db");
const User = sequelize.define(
"User",
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
isEmail: true,
},
username: {
type: DataTypes.STRING(15),
allowNull: false,
unique: true,
},
},
{
tableName: "users",
}
);
User.associate = (models) => {
User.belongsToMany(models.Product, {
through: models.ProductMember,
foreignKey: "user_id",
otherKey: "product_id",
});
User.hasMany(models.ProductMember, {
foreignKey: "user_id",
allowNull: false,
});
User.belongsToMany(models.Product, {
through: models.UserFavouriteProducts,
foreignKey: "user_id",
otherKey: "product_id",
});
}
module.exports = sequelize.model("User", User);
models/productMember.js:
const { DataTypes } = require("sequelize");
const sequelize = require("../db");
const ProductMember = sequelize.define(
"ProductMember",
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
isAdmin: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
},
{
tableName: "product_members",
}
);
ProductMember.associate = (models) => {
ProductMember.belongsTo(models.User);
ProductMember.belongsTo(models.Product);
};
module.exports = sequelize.model("ProductMember", ProductMember);
Update: Based on this post I updated the Db setup file to:
const fs = require('fs');
const path = require('path');
var basename = path.basename(module.filename);
const models = path.join(__dirname, '../models');
const db = {};
const Sequelize = require("sequelize");
const config = require("./db.config.js");
const sequelize = new Sequelize(config[process.env]);
fs
.readdirSync(models)
.filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function (file) {
var model = require(path.join(models, file))(
sequelize,
Sequelize.DataTypes
);
db[model.name] = model;
})
Object.keys(db).forEach(function (modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
})
db.Sequelize = Sequelize;
db.sequelize = sequelize;
module.exports = db;
Model file:
module.exports = (sequelize, Sequelize) => {
const Coupon = db.sequelize.define(
//... continue as it was
return Coupon;
}
So for the model file:
Wrapped it inside module.exports = (sequelize, Sequelize) => { }
return Coupon at the end
removed const sequelize = require("../db");
New problem: But with this new setup, Sequelize-related controller methods no longer work... For example for a controller file:
const User = require("../models/user");
const ensureLoggedIn = async (req, res, next) => {
...
const user = await User.findByPk(id);
it produces the error:
User.findByPk is not a function
I've tried adding const sequelize = require("../db"); to the controller file and then const user = await sequelize.User.findByPk(id); but that produced the same error.
I've tried adding const db = require("../db"); to the controller file and then const user = await db.sequelize.User.findByPk(id); but that produced the error "Cannot read property 'findByPk' of undefined".
First, you don't need to call sequelize.model to get a model that registered in Sequelize, you can just export a return value from sequelize.define:
const Product = sequelize.define(
"Product",
...
module.exports = Product;
Second, it seems you didn't call associate methods of all registered models.
Look at my answer here to get an idea of how to do it.
Update: to use models if you defined them like in my answer you need to access them like this:
const { sequelize } = require("../db");
const user = await sequelize.models.User.findByPk(id);
...
I'm having a trouble where I couldn't access the relationship data table from NodeJS PostgreSQL and Express.
First of all here is my simple table :
As you can see, my "jenis" table has association with "kategori" table, one jenis can have multiple kategori, and one kategori should only contain one jenis.
Here is my migration on Postgres Sequelize :
jenis-migration.js
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable("Umkm_Jenis", {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
nama: {
type: Sequelize.STRING,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable("Umkm_Jenis");
},
};
kategori-migration.js
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable("Umkm_Kategori", {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
jenis_id: {
type: Sequelize.INTEGER,
allowNull: false,
},
nama: {
type: Sequelize.STRING,
allowNull: false,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable("Umkm_Kategori");
},
};
jenis.model.js
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Umkm_Jenis extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
this.hasMany(models.Umkm_Kategori, {
foreignKey: "jenis_id",
as: "umkm_kategori",
});
}
}
Umkm_Jenis.init(
{
nama: DataTypes.STRING,
},
{
sequelize,
modelName: "Umkm_Jenis",
freezeTableName: true,
}
);
return Umkm_Jenis;
};
kategori-model.js
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Umkm_Kategori extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
this.belongsTo(models.Umkm_Jenis, {
foreignKey: "jenis_id",
as: "umkm_jenis",
});
}
}
Umkm_Kategori.init(
{
jenis_id: DataTypes.INTEGER,
nama: DataTypes.STRING,
},
{
sequelize,
modelName: "Umkm_Kategori",
freezeTableName: true,
}
);
return Umkm_Kategori;
};
I have created some seeder data on postgres for both jenis and kategori table.
Now I want my getAllKategori API to actually include the value from "jenis" table using the relationship that I have made. Below is my apiController for kategori :
exports.findAllKategori = async (req, res) => {
//check if theres a filter applied
const nama = req.query.nama;
const condition = nama ? { nama: { [Op.iLike]: `%${nama}%` } } : null;
try {
const response = Kategori.findAll({
where: condition,
include: [{ model: db.jenis, as: "umkm_jenis", required: false }],
});
const data = await response;
return res.status(200).send(data);
} catch (error) {
console.log(error);
return res.status(500).send(error);
}
};
But when I tried to hit the API from POSTMAN, it shows SequelizeEagerLoadingError.
If I commented this line on kategoriController :
include: [{ model: db.jenis, as: "umkm_jenis", required: false }],
and then try to hit the api once more, it successfully shows all my data.
I have already read some similar question in this forum but none of it seems to work.
Thank you for taking your time!
UPDATE
Below is the models/index.js file
"use strict";
const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || "development";
const config = require(__dirname + "/../config/config.json")[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(
config.database,
config.username,
config.password,
config
);
}
fs.readdirSync(__dirname)
.filter((file) => {
return (
file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js"
);
})
.forEach((file) => {
const model = require(path.join(__dirname, file))(
sequelize,
Sequelize.DataTypes
);
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
db.kategori = require("./umkm_kategori")(sequelize, Sequelize);
db.jenis = require("./umkm_jenis")(sequelize, Sequelize);
db.produk = require("./umkm_produk")(sequelize, Sequelize);
db.review = require("./umkm_review")(sequelize, Sequelize);
module.exports = db;
console.log(error)
You already registered all models and associations with this code pieces:
const model = require(path.join(__dirname, file))(
sequelize,
Sequelize.DataTypes
);
db[model.name] = model;
and
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
so this code is registering models once again, just remove it and use model names defined above.
db.kategori = require("./umkm_kategori")(sequelize, Sequelize);
db.jenis = require("./umkm_jenis")(sequelize, Sequelize);
db.produk = require("./umkm_produk")(sequelize, Sequelize);
db.review = require("./umkm_review")(sequelize, Sequelize);
I've been trying to create associations with Sequelize but to no avail, I kept getting a hasOne is not a function error. I've learned that it may be because of circular dependencies with my imports. So I started using the Sequelize instance in my index.js file and importing that instance in other model files:
index.js:
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
const practAppt = require('./practAppt')
const practUser = require('./practUsers')
practAppt.hasOne(practUser, {foreignKey: "email"})
practUser.hasMany(practAppt, {foreignKey: "client"})
var sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'C:/backend/db.sqlite3'
});
//let sequelize;
// if (config.use_env_variable) {
// sequelize = new Sequelize(process.env[config.use_env_variable], config);
// } else {
// sequelize = new Sequelize(config.database, config.username, config.password, config);
// }
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
console.log("FILE", file)
const model = require((path.join(__dirname, file)));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
practUsers.js
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const db = require("./index")
const practUser = db.define("practUsers", {
// attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING,
allowNull: false
},
address: {
type: Sequelize.STRING,
allowNull: false
},
unit: {
type: Sequelize.STRING,
allowNull: false
},
city: {
type: Sequelize.STRING,
allowNull: false
},
province: {
type: Sequelize.STRING,
allowNull: false
},
postal_code: {
type: Sequelize.STRING,
allowNull: false
},
phoneNumber: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
birthdate: {
type: Sequelize.STRING,
allowNull: false
},
healthCardNumber: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
profession: {
type: Sequelize.STRING,
allowNull: false
},
designation: {
type: Sequelize.STRING,
allowNull: false
},
userType: {
type: Sequelize.STRING,
allowNull: false
},
})
// automatically create the table with the model definition
//sequelize.sync()
// test the connections
module.exports = {practUser}
But now it's telling me db.define is not a function, even if I export sequelize in index.js I get the same error. How do I properly create associations? I should create them in index.js correct? Or does it not matter? The docs seems to be useless on this front.
your db object as exported from index.js doesn't have the define method. You probably need to write:
const practUser = db.sequelize.define(....
I have 3 tables: User, Trip, authoriseDate.
here is associate:
A user has many trips and a user has one authoriseDate
User one to many Trips
User one to one authoriseDate
and here is the models
User
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define('User', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
email: { type: DataTypes.STRING(50), unique: true },
phoneNumber: {
type: DataTypes.STRING(12), unique: true,
},
}, {
classMethods: {
associate(models) {
// associations can be defined here
user.hasOne(models.authoriseDate, { foreignKey: 'userId' });
user.hasMany(models.Trip, { foreignKey: 'userId' });
},
},
});
return user;
};
Trip
module.exports = (sequelize, DataTypes) => {
const trip = sequelize.define('Trip', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
userId: DataTypes.INTEGER,
status: DataTypes.INTEGER,
}, {
classMethods: {
associate(models) {
// associations can be defined here
trip.belongsTo(models.User, { foreignKey: 'userId' });
},
},
});
return trip;
};
authoriseDate
module.exports = (sequelize, DataTypes) => {
const authoriseDate = sequelize.define('AuthoriseDate', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
userId: DataTypes.INTEGER,
lastAuthorise: DataTypes.DATE,
}, {
classMethods: {
associate(models) {
// associations can be defined here
authoriseDate.belongsTo(models.User, { foreignKey: 'userId', });
},
},
});
return authoriseDate;
};
but when I using findAll function
models.User.findAll({
include: [{
model: models.Trip,
},
{
model: models.authoriseDate,
}],
})
here is my model file
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
//var env = process.env.NODE_ENV || 'development';
//var config = require(__dirname + './../../../config/config.json')[env];
var config = require('../../config/env')
var db = {};
// if (config.use_env_variable) {
// var sequelize = new Sequelize(process.env[config.use_env_variable]);
// } else {
// var sequelize = new Sequelize(config.database, config.username, config.password, config);
// }
var sequelize = new Sequelize(config.dbName, config.dbUserName, config.dbPassword, {
host: config.dbHost,
dialect: config.dbDialect,
});
fs
.readdirSync(__dirname)
.filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== basename);
})
.forEach(function (file) {
if (file.slice(-3) !== '.js') return;
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function (modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
I am getting the errors:
Unhandled rejection SequelizeEagerLoadingError: Trip is not associated to User, and Cannot read property 'getTableName' of undefined
I don't know how to solve these errors, anyone help me please
You need to call a function associate.
Example:
AuthoriseDate model
module.exports = (sequelize, DataTypes) => {
const authoriseDate = sequelize.define('AuthoriseDate', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
userId: DataTypes.INTEGER,
lastAuthorise: DataTypes.DATE,
});
authoriseDate.associate = (models) => {
// associations can be defined here
authoriseDate.belongsTo(models.User, { foreignKey: 'userId', });
};
return authoriseDate;
};
Trip Model
module.exports = (sequelize, DataTypes) => {
const trip = sequelize.define('Trip', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
userId: DataTypes.INTEGER,
status: DataTypes.INTEGER,
});
trip.associate = (models) => {
// associations can be defined here
trip.belongsTo(models.User, { foreignKey: 'userId' });
};
return trip;
};
User Model
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define('User', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
email: { type: DataTypes.STRING(50), unique: true },
phoneNumber: {
type: DataTypes.STRING(12), unique: true,
},
});
user.associate = (models) => {
// associations can be defined here
user.hasOne(models.AuthoriseDate, { foreignKey: 'userId' });
user.hasMany(models.Trip, { foreignKey: 'userId' });
};
return user;
};
init models
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
//var env = process.env.NODE_ENV || 'development';
//var config = require(__dirname + './../../../config/config.json')[env];
// var config = require('../../config/env')
var db = {};
var sequelize = new Sequelize('test_01', 'root', 'root', {
host: 'localhost',
dialect: 'mysql',
});
fs
.readdirSync(__dirname)
.filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== basename);
})
.forEach(function (file) {
if (file.slice(-3) !== '.js') return;
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
console.log(db);
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
(async () => {
await sequelize.sync();
})();
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
use find
(async () => {
const models = require('./models');
const users = await models.User.findAll({
include: [
{
model: models.Trip,
},
{
model: models.AuthoriseDate,
},
],
});
console.log(users);
})();
http://docs.sequelizejs.com/manual/tutorial/associations.html