skip to Main Content

I’m a beginner in creating APIs with NodeJS and Sequelize.
Before coming here I searched for my problem on several forums/docs but I always get the same result.

As you can see in my result, I always get "fuelId: 1".
Instead of this, I would like it to display the information of this foreign key 1. That is to say the name of this fuel and its information.

PS: I removed parts of non-useful code otherwise stack overflow told me that I was posting too much code

MyControllers.js:

const sequelize = require('../db/sequelize')
    const getAll = (req, res) => {
        const modelName = req.params.modelName;
        const Model = sequelize[modelName];
        if (!Model) {
            const message = `Le modèle "${modelName}" n'existe pas.`;
            return res.status(404).json({ message });
        }
            Model.findAndCountAll({
                include: [
                    {
                        model: sequelize['fuels'],
                        foreignKey: 'fuelId',
                        as: 'fuels',
                        attributes: ['id','name']
                    }
                ]
            })
                .then(items => {
                    const status = 200
                    const isSuccess = true
                    const message = 'La liste a bien été récupérée.'
                    const total = items.count
                    res.json({ isSuccess, status, message, total, results: items })
                })
    } 

Sequelize.js:

const { Sequelize, DataTypes } = require('sequelize');
const FuelModel = require('../models/fuel');
const CarModel = require('../models/car');
const fuelMock = require('./mocks/mock-fuel');
const carMock = require('./mocks/mock-cars');
const fuels = FuelModel(sequelize, DataTypes);
const cars = CarModel(sequelize, DataTypes);

fuels.hasMany(cars, {foreignKey: 'fuelId', as: 'cars'});
cars.belongsTo(fuels, {foreignKey: 'fuelId', as: "fuels"});

const initDb = async () => {
    const _ = await sequelize.sync({ force: true })
    fuelMock.map(fuel => {
        fuels.create({
            name: fuel.name
        })
    })
    carMock.map(car => {
        cars.create({
            name: car.name,
            picture: car.picture,
            power: car.power,
            horses: car.horses,
            kms: car.kms,
            first_registration: car.first_registration,
            seating_places: car.seating_places,
            doors: car.doors,
            co2: car.co2,
            price: car.price,
            fuelId: car.fuelId,
        })
        .then(car => console.log(JSON.stringify(car)))
    })
}

module.exports = { 
    initDb, fuels,cars
}

My result:

        "rows": [
          {
            "id": 1,
            "name": "AUDI | A1 | SPORTBACK 30 TFSI S-LINE 1",
            "picture": "annonces/1200x900/53188-dlTXSoYqsnthVjFPwkfg.jpg",
            "power": 81,
            "horses": 110,
            "kms": 11400,
            "first_registration": "03-2023",
            "seating_places": 5,
            "doors": 5,
            "co2": 125,
            "price": 24980,
            "created": "2024-02-26T12:25:16.000Z",
            "fuelId": 1
          },
}

My car model :

    module.exports = (sequelize, DataTypes) => {
        const Car = sequelize.define('Car', {
            id: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            name: {
                type: DataTypes.STRING,
                allowNull: false,
                unique: {
                    msg: 'Le nom est déjà pris.'
                },
                validate: {
                    notEmpty: { msg: 'Le nom ne peut pas être vide' },
                    notNull: { msg: 'Le nom est une propriété requise' }
                }
            },
            picture: {
                type: DataTypes.STRING,
                allowNull: false,
                validate: {
                    isUrl: { msg: 'Utilisez uniquement une URL valide pour l'image.' },
                    notNull: { msg: 'L'image est une propriété requise' }
                }
            },
            power: {
                type: DataTypes.INTEGER,
                allowNull: false,
            },
            horses: {
                type: DataTypes.INTEGER,
                allowNull: false,
            },
            kms: {
                type: DataTypes.INTEGER,
                allowNull: false,
            },
            first_registration: {
                type: DataTypes.STRING,
                allowNull: false,
            },
            seating_places: {
                type: DataTypes.INTEGER,
                allowNull: false,
            },
            doors: {
                type: DataTypes.INTEGER,
                allowNull: false,
            },
            co2: {
                type: DataTypes.INTEGER,
                allowNull: false,
            },
            price: {
                type: DataTypes.INTEGER,
                allowNull: false,
            }, {
        timestamps: true,
        createdAt: 'created',
        updatedAt: false,
        tableName: 'cars'
    })

    return Car
}

My Fuel model

module.exports = (sequelize, DataTypes) => {
    const Fuel =  sequelize.define('Fuel', {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false,
      },
    }, {
      timestamps: true,
      createdAt: 'created',
      updatedAt: false,
        tableName: 'fuels'
    })

    return Fuel
  }

2

Answers


  1. Chosen as BEST ANSWER

    Finally, after several tests and searches, I discovered that my Fuel Model was not properly searched in the include of my function. It is therefore not necessary to modify the then


  2. This is a follow up on the comment on how to issue another query to fetch fuel details

    const initDb = async () => {
        const _ = await sequelize.sync({ force: true })
        fuelMock.map(fuel => {
            fuels.create({
                name: fuel.name
            })
        })
        carMock.map(car => {
            cars.create({
                name: car.name,
                picture: car.picture,
                power: car.power,
                horses: car.horses,
                kms: car.kms,
                first_registration: car.first_registration,
                seating_places: car.seating_places,
                doors: car.doors,
                co2: car.co2,
                price: car.price,
                fuelId: car.fuelId,
            })
                .then((car) => {
                    const fuelDetail = fuels.findOne({
                        where: {
                            id: car.fuelId
                        }
                    })
                    
                    car.fuel_name = fuelDetail.name
                    console.log(JSON.stringify(car))
                })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search