4

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.

2 Answers 2

6

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.

1
  • Thank you very much, it helped a lot! I'm using ES6, tested it now and I get what I need to. Commented Sep 24, 2017 at 20:01
1

Thank you - I am passing parameters right from req.body and this worked perfectly for me so I am posting it in the event that it may save someone time.

app.post('/doFind', (req, res) => {
    Abrigos.findAll(
      {[req.body.field]: req.body.newVal},
      {returning: true, where: {id: req.body.id}}
    )
    .then( () => {
      res.status(200).end()
    })
    .catch(err => {
      console.log("Err: " + err)
      res.status(404).send('Error attempting to update database').end()
    })
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.