node.js - Express API REST 过滤数据 MongoDB

标签 node.js mongodb express mongoose mongodb-query

我有一个带有 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/

相关文章:

node.js - 在node-webkit中显示状态栏

javascript - RegExp 构造函数转义斜杠字符但不转义点

javascript - 如何为 Node.js REST API 正确配置 Nginx?

javascript - 分隔数组的水线查询 "OR"

java - 有没有办法将mongodb数据库公开为rest api

mongodb - 如何处理 MongoDB/DynamoDB 中的循环文档?

node.js - 无需 Passport 认证

javascript - 将node.js代码编译为非node需要的代码

jquery - 模拟 POST 请求

javascript - node.js:将mysql(npm)池输出到html或jade