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

基于URL参数的Express.js查询:按分类获取MongoDB数据

解决方案

你不需要用findById,这个方法是根据文档的_id字段查询的,而你需要按category字段筛选数据,用find()方法并传入查询条件即可。下面提供两种实现方式:

方式一:动态路由(推荐)

用动态路由参数匹配不同分类,后续新增分类时无需额外添加路由:

router.get('/:category', async (req, res) => {
    try {
        // 从URL参数中获取分类名称
        const categoryName = req.params.category;
        // 根据category字段筛选对应数据
        const data = await Model.find({ category: categoryName });
        res.json(data);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

访问localhost:3000/phones时,req.params.category会取到phones,返回所有category为phones的数据;访问localhost:3000/laptops同理。

方式二:单独定义路由

如果只需要固定支持phones和laptops两个分类,可分别定义路由:

// 获取phones分类数据
router.get('/phones', async (req, res) => {
    try {
        const data = await Model.find({ category: 'phones' });
        res.json(data);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

// 获取laptops分类数据
router.get('/laptops', async (req, res) => {
    try {
        const data = await Model.find({ category: 'laptops' });
        res.json(data);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

注:原来的/getAll路由可保留,它仍会返回所有数据,不影响新路由的使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:25:21