javascript 如何在mongoose中查找嵌套属性

yftpprvb  于 2023-02-07  发布在  Java
关注(0)|答案(2)|浏览(104)

hi我有如下的mongodb文档:

{
    _id: ObjectId("63df40c651f1358f2b60f24a"),
    origin: {
      country: 'Usa',
      state: 'Washington',
      city: 'Washington',
      type: 'Point',
      coordinates: [ 12.555, 18.645 ]
    },
    destination: {
      country: 'Usa',
      state: 'Montana',
      city: 'Yellowstone',
      type: 'Point',
      coordinates: [ 12.555, 20.645 ]
    },
    date: 'mon 2023-12-16',
    seats: 4,
    status: 'pending',
    driver: {
      firstName: 'sam',
      lastName: 'johnson',
      phoneNumber: '92823831736',
      socialNumber: '1381222327',
      driverId: '63d8f94202653dc3592a0aa4'
    },

我使用下面的网址和代码查找基于目的地的位置:
URL:“本地主机:3000/API/v1/travel/?州=蒙大拿州&城市=黄石公园”
我的密码是

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;
  }
  const travelList = await Travel.find({ destination:queryObject });
  res.status(StatusCodes.OK).json({ status: "success", travelList });
};

我希望取回我的文档,但得到的响应却是空列表:

{
  "status": "success",
  "travelList": []
}

请帮我解决这个问题

omjgkv6w

omjgkv6w1#

检查代码的这一行:

const travelList = await Travel.find({ destination:queryObject });

您已经在queryObject中定义了destination。因此,您应该

await Travel.find(queryObject);

请注意,查询默认情况下是区分大小写的,所以大小写很重要。

lztngnrs

lztngnrs2#

您正确地创建了一个过滤器。但是,您应该只执行find(queryObject)而不是find({ destination: queryObject }),因为queryObject已经包含了destination属性。

const travelList = await Travel.find(queryObject);

相关问题