Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use query parameter as col name on sequelize query

So, I have an Express server running Sequelize ORM. Client will answer some questions with radio button options, and the answers is passed as query parameters to the URL, so I can make a GET request to server.

The thing is: my req.query values are supposed to be the column names for my database table. I want to know if it's possible to get the response from the database using Sequelize, and passing the parameters as the column name of the table.

async indexAbrigo(req, res) {
  try {
    let abrigos = null
    let type = req.query.type  // type = 'periodoTEMPORARIO'
    let reason = req.query.reason // reason = 'motivoRUA'
    abrigos = await Abrigos.findAll({
      attributes: ['idABRIGOS'],
        where: {
//I want type and reason to be the parameters that I got from client
          type: 'S',
          reason: 'S'
        }
      })
  }
  res.send(abrigos)
}

This is not working, the result of the query is something like

(SELECT `idABRIGOS` FROM Abrigos WHERE `type` = `S` AND `reason` = `S`)

Instead, I need that type and reason get translated to their values, and these values will be passed to the SQL. Is it possible to do with Sequelize? Or is it even possible with any ORM for Node/Express?

Thanks.

like image 653
Artur Mello Avatar asked Mar 09 '23 00:03

Artur Mello


1 Answers

Yes, you can do it with computed property names. It would look like this:

where: {
  [type]: 'S',
  [reason]: 'S'
}

Your node.js version must be compatible with ES6.

like image 163
cassini Avatar answered Mar 11 '23 04:03

cassini