my association is not showing in my rest API built in Sequelize and nodejs and express where I have defined the association in the database

Viewed 56

I'm trying to show the table of star category in my stars table when I call the url in postman, here I'm trying to define that the star category has one too many relationships with stars, and the star belongs to the star category. When I call the get method of stars even though I think I have defined the relationship it will load the validation of stars cannot be loaded instead of displaying the star recorded then its associated variables regarding what the star belongs to

'star model'
    'use strict';
    const {
      Model
    } = require('sequelize');
    module.exports = (sequelize, DataTypes) => {
      class Star 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
           Star.belongsTo(models.star_Categories,
               {
                 foreignKey:{
                   allowNull:false
                 }
             })
        }
      };
      Star.init({
        name: DataTypes.STRING,
        discovery_name: DataTypes.STRING,
        imageFileName: DataTypes.STRING,
        datediscovered: DataTypes.DATE,
        colour: DataTypes.STRING,
        mass: DataTypes.NUMERIC,
        dfe: DataTypes.NUMERIC,
        galaxy_origin: DataTypes.STRING,
        star_categories_id: DataTypes.INTEGER
      }, {
        sequelize,
        modelName: 'Star',
      });
      return Star;
    }; 

'star_Categories model'

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class star_Categories 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


       star_Categories.hasMany(models.Star,{
        onDelete:'CASCADE',
         onUpdate:'CASCADE'
       })


    }
  };
  star_Categories.init({
    type: DataTypes.STRING,
    description: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'star_Categories',
  });
  return star_Categories;
};

'star Controller'

//define all the logic regarding post
//import to our models
const models = require('../models');
//new method to insert star records
function saveStar(req, res){    //creates a star
    //create a new object to insert into the table
    const star = {
        name: req.body.name, //i want to get the name from the incoming request
        discovery_name: req.body.discovery_name,
        imageFileName: req.body.imageFileName,
        datediscovered: req.body.datediscovered,
        colour: req.body.colour,
        mass: req.body.mass,
        dfe: req.body.dfe, //distance from Earth
        galaxy_origin: req.body.galaxy_origin,
        star_categories_id:req.body.star_categories_id
    }

    // const star_Categories = {
    //     type: req.body.type, //i want to get the name from the incoming request
    //     description: req.body.description
    // }


 //select the star model
    //create star record
 models.Star.create(star).then(result =>{
 res.status(201).json({
    message: "Star created good job ",
     star: result
 });
     //if error
 }).catch(error =>{
     res.status(505).json({
         message: "Star cannot be created ",
         error: error
     });

 });

}

//this function will show the data to the user
function showStars(req, res){
   //to get an record we need and id of it
    const id = req.params.id; //here we can get the id

    models.Star.findByPk(id).then(result => {
         res.status(200).json({
            starss:result});  //successful response
         //if this returns an error
    }).catch(error => {
       res.status(500).json({
           message: "star id has not been found",
           error:error
       })
    });

}
// {include:['star_categories']}


function showAllstars(req, res){
  models.Star.findAll().then(result =>{
      res.status(200).json({
          starss:result
      });
  }).catch(error => {  //if there is an error
          res.status(500).json({
            message:"the stars cannot be loaded"
          });
  });



}

function  starUpdate(req,res){
//to update the star we need the star id
    const id = req.params.id; //here we can get the id
    const updatedStar = {
        //this will display the updated star details
        name: req.body.name, //i want to get the name from the incoming request
        discovery_name: req.body.discovery_name,
        imageFileName: req.body.imageFileName,
        datediscovered: req.body.datediscovered,
        colour: req.body.colour,
        mass: req.body.mass,
        dfe: req.body.dfe, //distance from Earth
        galaxy_origin: req.body.galaxy_origin,
        star_categories_id:req.body.star_categories_id
    }
    //this is how the star will be updated, where the id = to the id requested
    //column name and column value
    models.Star.update(updatedStar,{where:{id:id}}).then(result =>{  //passing what we want to update
        res.status(200).json({
            message:"Star Updated successfully ",
            // starss:result,
            star:updatedStar

        });
    }).catch(error => {
        res.status(500).json({
            message:"error updating the star make sure you specify the correct id that exists ",
            error:error
        });

    })

}

function killStar(req,res){
//we need to find the star id to delete the star
    const id = req.params.id; //here we can get the id
//find where the id is to delete the record
    models.Star.destroy({where:{id:id}}).then(result =>{
        res.status(200).json({
            message:"you have just killed a star you monster! ",
            star:result
        });

    }).catch(error=> {
        res.status(500).json({
            message: "error updating the star make sure you specify the correct id that exists ",
            error: error
        });
    });
}


//export methods so other files can use these methods
module.exports ={
    //to use the save method we are going to export
    saveStar:saveStar,
    showStars:showStars,
    showAllstars:showAllstars,
    starUpdate:starUpdate,
    killStar:killStar


    // index: index

}


// function index(req, res){
// //list all the stars on our database
//     const stars = "Stars list";
//     res.send(stars); //pass the star string
// }
//n
0 Answers
Related