如何通过type类型参数查询对应API接口的返回数据
按type字段查询API实现步骤
后端接口实现
新增专门的按类型查询的路由即可,不需要使用JSON.stringify处理参数,路由参数本身会以字符串形式传递,直接传入Mongoose查询条件即可:
// 新增按type查询的接口 router.get('/getByType/:type', async (req, res) => { try { // 用find方法匹配type字段,支持返回多条同类型的数据 const result = await Excuse.find({ type: req.params.type }) res.json(result) } catch (err) { res.status(500).json({ error: '查询失败' }) } })
如果希望兼容现有查询逻辑,也可以通过查询参数实现单接口同时支持id和type查询:
router.get('/get', async (req, res) => { try { const query = {} if (req.query.id) query._id = req.query.id if (req.query.type) query.type = req.query.type const result = await Excuse.find(query) res.json(result) } catch (err) { res.status(500).json({ error: '查询失败' }) } })
前端调用方式
- 路径参数方式调用:访问
www.helloworld.com/getByType/commentary即可返回所有type为commentary的数据 - 查询参数方式调用:访问
www.helloworld.com/get?type=commentary即可返回对应类型数据
常见问题说明
你之前使用JSON.stringify不生效是因为该方法是用来将JS对象转换为JSON字符串的,你直接传递type的原始字符串值即可满足查询需求,不需要额外做序列化处理。
- 如果需要模糊匹配type,可以将查询条件替换为
{ type: { $regex: req.params.type, $options: 'i' } },可实现不区分大小写的部分匹配 - 注意查询的type值要和数据库中存储的内容完全匹配(大小写、特殊字符都需要一致)才能查询到结果
内容的提问来源于stack exchange,提问作者Jonathan
相关产品推荐
相关产品推荐

