Mongoose嵌套属性查询求助:按目的地筛选返回空列表
问题分析与解决方案
问题根源
你的代码在构造查询条件时出现了结构错误:
- 你给
queryObject添加了destination子属性(比如queryObject.destination.state = state),最终queryObject的结构是{ destination: { state: "Montana", city: "Yellowstone" } } - 随后调用
Travel.find({ destination: queryObject }),生成的查询条件变成了:
这个条件完全不匹配文档结构(文档里的{ destination: { destination: { state: "Montana", city: "Yellowstone" } } }destination是包含country/state/city等字段的对象,而非嵌套了另一个destination的对象),因此返回空列表。
修正方案
以下两种方式都能正确构造查询条件:
方式一:使用点符号(推荐)
直接用点符号指定嵌套字段,构造查询对象:
const Travel = require("../models/travel-model"); const getAllTravelsByDestination = async (req, res) => { const { country, state, city } = req.query; const queryObject = {}; if (country) { queryObject["destination.country"] = country; } if (state) { queryObject["destination.state"] = state; } if (city) { queryObject["destination.city"] = city; } // 直接传入queryObject作为查询条件 const travelList = await Travel.find(queryObject); res.status(StatusCodes.OK).json({ status: "success", travelList }); };
方式二:使用嵌套对象结构
直接构造destination的子字段查询,避免多余的嵌套:
const Travel = require("../models/travel-model"); const getAllTravelsByDestination = async (req, res) => { const { country, state, city } = req.query; const queryObject = { destination: {} }; if (country) { queryObject.destination.country = country; } if (state) { queryObject.destination.state = state; } if (city) { queryObject.destination.city = city; } // 直接传入queryObject作为查询条件 const travelList = await Travel.find(queryObject); res.status(StatusCodes.OK).json({ status: "success", travelList }); };
验证说明
两种方式最终生成的有效查询条件为:
{ "destination.state": "Montana", "destination.city": "Yellowstone" }
或嵌套对象形式:
{ destination: { state: "Montana", city: "Yellowstone" } }
这两种形式都会匹配文档中destination字段下对应值的记录,不受destination包含的其他字段(如type、coordinates)影响。
内容的提问来源于stack exchange,提问作者Quantum-script
相关产品推荐
相关产品推荐

