3

I have a Pokemon API REST with express and mongo. Im trying to filter pokemon by his type.

I send from Angular a http GET with the type to filter on params.

Having the following controller.js

const pokemons = require('../models/pokemon');
const laboratoryCtrl = {};

laboratoryCtrl.filterPokemon = async (req, res) => {
  const filterType = req.query.type; // filterType = "Fire"
  const pokemon = await pokemons.find({ $or : [{type: /^Fire/}, {type2: /^Fire/}] })
   .sort({ pokedex: + 1 });
      res.json(pokemon);
   }

module.exports = laboratoryCtrl;

How can I use the value of "filterType" thats actually Fire in the .find() method?

Is this a good way of filtering data? this is my first API REST and my first express + mongo project

1 Answer 1

1

Use the RegExp constructor to create a regular expression instance with the filterType variable:

const rgx = new RegExp(`^${req.query.type}`); //or new RegExp('^'+req.query.type)
const pokemon = await pokemons.find({ 
    '$or': [
        { 'type' : rgx }, 
        { 'type2': rgx }
    ] 
}).sort({ pokedex: + 1 });
res.json(pokemon);
Sign up to request clarification or add additional context in comments.

5 Comments

hey @chridam can you help me again? how can i do the same but this time with the sort() method and the pokedex property, im getting /pokedex/ always, i just need "pokedex"
nvm i found the solution, i share so maybe others can use it const filterStat = new Object(); filterStat[req.query.type] = + 1;
hey its me again! if I dont select a Type to filter, how can I set using Regexp the equivalent * on SQL? /^*/ /^''/ /^%/ not working
You will have to escape it with a backlash e.g new RegExp("^\\*")
With your info i could search better and found the solution /.*?/

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.