Reputation: 793
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
Upvotes: 3
Views: 3086
Reputation: 103445
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);
Upvotes: 1