我有一个带有 express 和 mongo 的 Pokemon API REST。我正在尝试按他的类型过滤口袋妖怪。
我从 Angular 发送一个 http GET,其中包含要过滤参数的类型。
有以下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;
如何在 .find() 方法中使用实际 Fire 的“filterType”值?
这是过滤数据的好方法吗?这是我的第一个 API REST 和我的第一个 express + mongo 项目
最佳答案
使用 RegExp
构造函数以使用 filterType
变量创建正则表达式实例:
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);
关于node.js - Express API REST 过滤数据 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51730198/