Nadine
Nadine

Reputation: 357

Sequelize Query FindAll doesn't filter

I created a rest api '/getSingleAxisByInstance' which takes an instanceid and should get all devices with this instanceid from a MySQL database of the table 'Devices'.

router.get('/getDeviceByInstance', (req, res) => {
    Device.findAll({where: {instanceid: req.body.instanceid}})
        .then(device=> {
            res.status(200).send(device);
        })
        .catch(err => res.status(400).json({message: 'Error', err}));
});

But it doesn't filter the rows, it just returns all row from the table independent from the instanceid.. The filtering does work when I add 'attributes' to the query like so:

Device.findAll({attributes: ['instanceid', 'name', 'deviceId']},
        {where: {instanceid: req.body.instanceid}})

The problem is that with this code I can't use the REST Api from the frontend. When I add the attributes to the configuration the query fails everytime. When I remove attributes from the configuration it works fine.

The frontend code with the axios request:

export const getDeviceByInstance = myInstance => {
    return axios
        .get('/device/getDeviceByInstance', {
            instanceId: myInstance.instanceId
        })
        .then((res => {
            return res;
        }))
        .catch(err => {
            return err;
        })
};

My model code for the Device table:

const Sequelize = require('sequelize');
const db = require('../config/mainDatabase');


const Device= db.define('device', {
    deviceId: {type: Sequelize.INTEGER, primaryKey: true},
    name: {type: Sequelize.STRING},
    instanceId: {type: Sequelize.INTEGER},
});
module.exports = Device;

What am I missing? Thank you in advance!

Upvotes: 1

Views: 1005

Answers (1)

Prakash Karena
Prakash Karena

Reputation: 2595

Problem is you are passing your data in body in get request.

Solution 1 : change your get request to post

  return axios
        .post('/device/getDeviceByInstance', { // change it to post 
            instanceId: myInstance.instanceId
        })

Also make your route as post

   router.post('/getDeviceByInstance', (req, res) => {  // change post route 

Solution 2 : you can pass your data with get request as query/params

     //frontend
     axios 
     .get(`/device/getDeviceByInstance/${myInstance.instanceId}`)
     .then().catch();

     //backend 
     router.get('/getDeviceByInstance/:instanceId', (req, res) => {  // change you route 

             const instanceId = req.params.instanceId; // you can access it as 
       ..........

      }

Upvotes: 1

Related Questions