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

Mongoose嵌套属性查询求助:按目的地筛选返回空列表

问题分析与解决方案

问题根源

你的代码在构造查询条件时出现了结构错误:

  1. 你给queryObject添加了destination子属性(比如queryObject.destination.state = state),最终queryObject的结构是{ destination: { state: "Montana", city: "Yellowstone" } }
  2. 随后调用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:55:18