Skip to content
Advertisement

How to use Sequelize associations with .then in controller

This is my ToWatch Model in toWatch-model.js file which in code has UserModel->ToWatch 1:1 relationship and has ToWatch->MovieModel 1:M relationship.

const Sequelize = require('sequelize');
const sequelize = require('./../common/db-config');
const MovieModel = require ("./movie-model");
const UserModel = require("./user-model");

const Model = Sequelize.Model;
class ToWatch extends Model{}

ToWatch.init({
  id: {
    type: Sequelize.INTEGER, 
    allowNull: false, 
    primaryKey: true, 
    autoIncrement: true, 
    field: 'id_towatch'
},
  date: {
    type: Sequelize.DATE, 
    allowNull: false, 
    field: 'date'
},
  userId: {
    type: Sequelize.INTEGER,
    allowNull: false,
    field: 'id_user',
    references:{
      model: UserModel,
      key: "id"
    }
},  
  movieId: {
    type: Sequelize.INTEGER,
    allowNull: false,
    field: 'movie_id_towatch',
    references:{
      model: MovieModel,
      key: "id"
    }
}, 
}, 
{
    sequelize,
    modelName: 'towatch',
    tableName: 'towatch', 
    timestamps: false
    // options
  });

//Here is the relation ************

  UserModel.hasOne(ToWatch, {
    foreignKey: {
      type:Sequelize.DataTypes.INTEGER,
      allowNull:false,
      name:'fk_foreign_key_towatch'
    }
  });
  ToWatch.belongsTo(UserModel);

  ToWatch.hasMany(MovieModel, {
    foreignKey: {
      type:Sequelize.DataTypes.INTEGER,
      allowNull:false,
      name:'movie_id_towatch'
    }
  });
  MovieModel.belongsTo(ToWatch);
  
  module.exports = ToWatch;

I watched many tutorials, but being my first time trying to make a method that will return everything including something from my other table via ID, I wasn’t sure where to put and how to put data that I need in this method, considering it has .then(data=>res.send). Tutorials were doing it other ways by fetching or using async-await, and even documentation didn’t help me here. Can somebody tell me what to put and where inside this method, that is inside toWatch-controller.js file for me being able to see let’s say all the movie data (title,img,date) ,as an array I think, of the getToWatch method.

const ToWatch = require('./../models/toWatch-model');

  

module.exports.getToWatch = (req,res) => {
    ToWatch.findAll().then(toWatch => {
          
              [WHAT DO I PUT HERE?]

           res.send(toWatch);  
         }).catch(err => {
             res.send({
                 status: -1,
                 error:err
                 
             })
            
         })
}

I need something like this ToWatch{ color:red, cinema:”MoviePlace”, movieId{title:”Anabel”, img:”URL”, date:1999.02.23}

Advertisement

Answer

As I understood your question right, what you trying to do is return toWatch model instances with including User and Movie models. To do so you can pass options in findAll() method like below:

ToWatch.findAll({include: [{model: User}, {model: Movie}]})... //and rest of your code

Or alternatively to keep your code clean you can use scopes:

// below the toWatch-model.js file
ToWatch.addScope('userIncluded', {include: {model: User}})
ToWatch.addScope('movieIncluded', {include: {model: Movie}})

And in the getToWatch method:

// you can pass several scopes inside scopes method, its usefull when you want to combine query options
ToWatch.scopes('userIncluded', 'movieIncluded').findAll()... //rest of your code

For more information check out sequelize docs

Advertisement