【问题标题】:Sequelize Query FindAll doesn't filterSequelize Query FindAll 不过滤
【发布时间】:2020-05-13 17:32:50
【问题描述】:

我创建了一个 rest api '/getSingleAxisByInstance',它接受一个 instanceid 并且应该从表 'Devices' 的 MySQL 数据库中获取所有具有此 instanceid 的设备。

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}));
});

但它不会过滤行,它只是从独立于 instanceid 的表中返回所有行。 当我像这样向查询中添加“属性”时,过滤确实有效:

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

问题是我无法使用此代码从前端使用 REST Api。当我将属性添加到配置中时,查询每次都会失败。当我从配置中删除属性时,它工作正常。

带有axios请求的前端代码:

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

我的设备表型号代码:

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;

我错过了什么?提前谢谢!

【问题讨论】:

  • req.body 打印是否正确??

标签: javascript node.js reactjs axios sequelize.js


【解决方案1】:

问题是您在获取请求中传递了正文中的数据。

解决方案 1:将您的获取请求更改为发布

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

也将您的路线设为发布

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

解决方案 2:您可以使用 get 请求作为查询/参数传递数据

     //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 
       ..........

      }

【讨论】:

  • 如果您还有任何问题,请告诉我
  • 我用 post 试过了,但它仍然没有过滤设备。
  • 添加您更新的前端和后端代码。我会检查
  • 你确定。您正在后端获取您的 instanceId 吗?做 console.log('instanceId',instanceId);让我知道你是否得到了你的 instanceId
  • 是的,你是对的,当我在后端记录 instanceid 时它显示未定义,你知道这是为什么吗?我尝试了您的解决方案 2,效果很好,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-04-08
  • 2017-04-24
  • 2019-11-17
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 2021-06-05
  • 2019-09-06
相关资源
最近更新 更多