Home > Enterprise >  sequelize with where clause and order by together issue in Nodejs
sequelize with where clause and order by together issue in Nodejs

Time:09-10

I am trying to code Nodejs code to query my mySql database using sequelize

SQL code is SELECT * FROM quizzes WHERE category='Science' order by id DESC; which I want to formulate in sequelize but only where clause is executing order by not working in sequelize. Please help someone.

 Quiz.findAll({ where : {category:'Science'}},{order:['id','DESC']})
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving Quizs."
      });
    });

in console in see below code is executing

Executing (default): SELECT `id`, `question`, `optionA`, `optionB`, `optionC`, `optionD`, `answer`, `category`, `explanation`, `createdAt`, `updatedAt` FROM `quizzes` AS `quiz` WHERE `quiz`.`category` = 'Science';

CodePudding user response:

The sample code is passing in two distinct objects:

{ where : {category:'Science'}} and {order:['id','DESC']}

The query should be in a single object

Quiz.findAll({
  where: {
    category: 'Science',
  },
  order: [[ 'id', 'DESC' ]],
})
  • Related