You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于MongoDB编写REST API,支持React通过req.query批量获取多类别数据

基于MongoDB实现多类别数据查询的REST API

后端实现(Express + Mongoose)

1. 定义数据模型

创建包含category字段的Mongoose模型,用于存储分类数据:

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  name: String,
  price: Number,
  category: String, // 取值为man/women/kids等类别标识
  // 可添加其他业务字段
});

// 给category字段加索引,优化多类别查询性能
productSchema.index({ category: 1 });

module.exports = mongoose.model('Product', productSchema);

2. 编写API路由

创建处理多类别查询的GET接口,解析req.query中的类别参数,使用MongoDB的$in操作符匹配多个类别:

const express = require('express');
const router = express.Router();
const Product = require('../models/Product');

router.get('/products', async (req, res) => {
  try {
    const { categories } = req.query;
    const query = {};

    if (categories) {
      // 兼容两种传参方式:逗号分隔字符串或多重复参数
      const categoryList = Array.isArray(categories) 
        ? categories 
        : categories.split(',');
      query.category = { $in: categoryList };
    }

    const products = await Product.find(query);
    res.status(200).json(products);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;

前端React调用示例

方式1:逗号分隔类别字符串

const fetchMultiCategoryProducts = async () => {
  try {
    // 拼接查询参数,一次性指定多个类别
    const response = await fetch('/api/products?categories=man,women,kids');
    const products = await response.json();
    // 处理返回的多类别数据
    console.log(products);
  } catch (error) {
    console.error('数据查询失败:', error);
  }
};

方式2:多重复参数(更直观的数组传参)

const fetchMultiCategoryProducts = async () => {
  try {
    const params = new URLSearchParams();
    params.append('categories', 'man');
    params.append('categories', 'women');
    
    const response = await fetch(`/api/products?${params}`);
    const products = await response.json();
    console.log(products);
  } catch (error) {
    console.error('数据查询失败:', error);
  }
};

关键说明

  • $in操作符:MongoDB中用于匹配字段值在指定数组内的文档,完美适配多类别查询场景。
  • 参数兼容:后端同时支持两种传参格式,适配不同的前端传参习惯。
  • 性能优化:给category字段添加单字段索引,避免大数据量下的全表扫描。

内容的提问来源于stack exchange,提问作者Priyanka Dubey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 08:54:20