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

Mongoose如何按请求参数查询单文档中指定分类的对应数据

Mongoose按分类名查询仅返回对应items数组实现方法
  • 首先修正Schema定义
    你当前的Schema和实际存储的文档结构不匹配,会导致Mongoose查询时字段返回异常,先调整为和存储结构一致的定义:
const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const categorySchema = new Schema({
    name: {
        type: String,
        required: true
    },
    items: {
        type: Array,
        default: []
    }
})

module.exports = mongoose.model('categoryCollection', categorySchema)
  • 调整接口查询逻辑
    把硬编码的_id查询条件改为匹配传入的分类名和文档的name字段,通过MongoDB投影参数指定仅返回需要的items字段,避免传输多余字段,同时统一异步写法,补全异常和空值处理:
app.post('/targetCategory', async (req, res) => {
    try {
        const categoryName = req.body.category
        // 第二个参数为投影配置:1表示返回字段,0表示排除字段,此处仅返回items,过滤_id等多余字段
        const targetDoc = await categoryCollection.findOne(
            { name: categoryName },
            { items: 1, _id: 0 }
        )
        if (!targetDoc) {
            return res.status(404).send({ msg: "对应分类不存在" })
        }
        // 直接返回items数组,减少传输体积
        res.send(targetDoc.items)
    } catch (err) {
        console.log(err)
        res.status(500).send({ msg: "服务器查询错误" })
    }
})

补充说明:

  1. 如果需要改用GET请求传参,直接把req.body.category替换为req.query.category即可,前端可通过/targetCategory?category=cat1的形式拼接URL传参
  2. 投影规则可按需调整:比如需要同时返回分类名,就把投影配置改成{ items: 1, name: 1, _id: 0 }
  3. 上述代码统一使用async/await写法,和接口定义的async标记对齐,避免回调与异步写法混用导致的逻辑问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 08:51:27