0

I'm trying to build a relation between the users and his favorite cryptocurrency.

Meaning, multiple Users can have the same crypto as their favorites.

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
  }

These are my 2 tables at the moment and now I'm trying to build a relation between them. and I keep receiving this error on my console which I do not understand why.

I've edited multiple time to resolve the issue, This was the result with the help of Anatoly

CoinsUserRelations.js

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

    return CoinsUsersRelations
  }

I'm really unsure on why I get this error if I'm actually defining the model before creating the relations..

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

Edit part for a bug called 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
            })
        } 
    }
}

1 Answers1

0

You should register all models and only after that all their associations in one place. See my answer on a similar problem

Anatoly
  • 20,799
  • 3
  • 28
  • 42
  • Thank you for answering , I've edit my problem to show you how I did my index.js which is similar to yours except for the associations part. But, I do not understand how does your loop register my relations I made on CoinsUserRelations.js. It seems a bit weird to integrate since it seems you build your models in a different way than mine. –  May 28 '20 at 18:34
  • 1
    You should define associations like I pointed in my aswer. Also remove `const User = require('./User.js')` and `const Coin = require('./Coin.js')` from `CoinsUserRelations.js` – Anatoly May 28 '20 at 18:37
  • how would you use INCLUDE in this case ? –  Jun 15 '20 at 16:07
  • 1
    Like this: `const db = require('.\db.js') // where all registered models are stored const result = db.User.findAll({ include: [db.Coin] })` – Anatoly Jun 15 '20 at 18:00
  • Thanks sorry to disturb you again but I keep getting SequelizeEagerLoadingError this way. –  Jun 15 '20 at 18:17
  • 1
    Can you add the full description and stacktrace of this error? – Anatoly Jun 15 '20 at 18:18
  • At the bottom of the initial question I add the portion of the error. and I only get .SequelizeEagerLoadingError in my catch error. On my node.js console nothing appears. –  Jun 15 '20 at 18:20
  • 1
    Can you add a breakpoint on the `res.status(400).send({ error: err })` line and look at `err`? – Anatoly Jun 15 '20 at 18:23
  • Lol you're awesome I was able to retrieve what I wanted thank you. If I console.log my err before sending the request I would get the full result. Now I know what is my issue. I would upvote you 1000 time lol thank you. –  Jun 15 '20 at 18:43