Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express API REST Filter Data MongoDB

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

like image 299
Sergi Avatar asked Mar 09 '26 04:03

Sergi


1 Answers

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);
like image 171
chridam Avatar answered Mar 10 '26 18:03

chridam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!