用户和加密数据之间的关系 Sequelize 数据库

Relation between Users and cryptodata Sequelize database

我正在尝试在用户和他最喜欢的加密货币之间建立关系。

意思是,多个用户可以拥有与其收藏相同的加密货币。

Coin.js

module.exports = (sequelize, DataTypes) => {
    const Coin = sequelize.define('Coin', {
        cryptoName: DataTypes.STRING,
    })

    Coin.associate = function(models) {
     Coin.belongsToMany(models.CoinsUserRelations, {foreignKey: 'CoinID', through: 'CoinsUserRelations'})
    }

return Coin

}

User.js

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        firstName: DataTypes.STRING,
        lastName: DataTypes.STRING,
        email: {
           type: DataTypes.STRING,
           unique: true
        },
        password: DataTypes.STRING
        }, {
          hooks: {
           beforeSave: hashPassword
          }
     })

     User.associate = function(models) {
      User.belongsToMany(models.CoinsUserRelations, {foreignKey: 'UserID', through: 'CoinsUserRelations'})
     } 
     return User
  }

这些是我目前的 2 个表,现在我正在尝试在它们之间建立关系。我一直在我的控制台上收到这个错误,我不明白为什么。

我编辑了多次来解决这个问题,这是在 Anatoly 的帮助下得到的结果

CoinsUserRelations.js

module.exports = (sequelize, DataTypes) => {
    const CoinsUsersRelations = sequelize.define('CoinsUsersRelations', {
        UserID: {
            type: DataTypes.INTEGER,
        },
        CoinID: {
            type: DataTypes.INTEGER,
        }
    })

    return CoinsUsersRelations
  }

如果我在创建关系之前实际定义模型,我真的不确定为什么会出现此错误..

Index.js

const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const config = require('../config/config')
const db = {}

const sequelize = new Sequelize(
    config.db.database,
    config.db.user,
    config.db.password,
    config.db.options
)

fs
    .readdirSync(__dirname)
    .filter((file) => 
        file !== 'index.js'
    )
    .forEach((file) => {
        const 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

编辑名为 SequelizeEagerLoadingError

错误的部分
module.exports = {
    async getUserFavoriteCrypto (req, res) {
        try {
            const coins = await db.Users.findOne({
                where: {
                    UserID : req.query.userId
                },
                attributes: ['UserID'],
                include: [{
                    model: db.Coins,
                    required: false
                }]
            })
            console.log(coins)
            res.send({
                coins: coins
            })
        } catch (err) {
            res.status(400).send({
                error: err
            })
        } 
    }
}

您应该注册所有模型,然后才将它们的所有关联集中在一个地方。看我的