John Carlo
John Carlo

Reputation: 54

Search Operators in Sequelize

I wanted to display all of the data which have gains of greater than 1. But I seem to encounter problems on running the request on my postman with the url of :

http://localhost:3000/api/betHistory/winners

I get the result of:

Executing (default): SELECT `id`, `user_id`, `type`, `league_id`, `team_id`, `amount`, `gains`, `ratio`, `match_id`, `created_at`, `updated_at`, `updatedAt` FROM `bets` AS `bets` WHERE `bets`.`gains` = false;

which should be 'gains' '>' '1'

This is my bet.js

router.get('/winners', async (req, res) => {
  try {
    const data = req.params.gains;
    const bets = await BetRepository.getWinnersBets(data > 1);
    res.json(bets);
  } catch (error) {
   res.status(400).send('No data found');
  }
});

This is my BaseRepistory.js

findAll(fields) {
const options = {};
if (!!fields && fields) {
  options.attributes = fields;
 }
return this.model.findAll(options);
} 

And this is my BetRepository.js

const BaseRepository = require('../../../shared/repository/BaseRepository');
const Bet = require('../models/Bet');
const Op = require('sequelize').Op;

class BetRepository extends BaseRepository {
 constructor(model) {
  super(model);
}
getWinnersBets(gains, fields) {
  const options = {
   where: { gains }
 };
  if (!!fields && fields) {
   options.attributes = fields;
 }
 return this.model.findAll(options);
 }
}

module.exports = new BetRepository(Bet);

Any ideas on how to work with this? TYIA.

Upvotes: 1

Views: 511

Answers (2)

John Carlo
John Carlo

Reputation: 54

I have solved this problem by putting an operator on my getWinnersBets

getWinnersBets(fields) {
const options = {
  where: {
    gains: {
      [Op.gte]: 1
    }
  }
};
if (!!fields && fields) {
  options.attributes = fields;
 }
return this.model.findAll(options);
}

and removed the > 1 line on my const bets = await BetRepository.getWinnersBets(data > 1)

Upvotes: 0

Lukas
Lukas

Reputation: 10360

When you do getWinnersBets(data > 1);, you are not passing the expression data > 1 to getWinnersBets, you are passing getWinnersBets(true) or getWinnersBets(false) to it, so in your query you are actually querying

'gains' '=' 'true'

and not

'gains' '>' '1'

I don't know the API of model.findAll so I can't give you a pointer on how to pass that expression to findAll

Upvotes: 1

Related Questions