Search code examples
javascriptnode.jsmongodbexpressmongoose

How to search nested property in mongoose


hi I have mongodb document like below:

  {
    _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'
    },

I use below url and code for finding location base on destination:

URL: "localhost:3000/api/v1/travel/?state=Montana&city=Yellowstone"

and my code is:

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 });
};

I expect to get my document back but instead i get empty list as response:

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

please help me for this problam


Solution

  • You created a filter properly. But, instead of find({ destination: queryObject }), you should only do find(queryObject), since the queryObject already contains the destination property.

    const travelList = await Travel.find(queryObject);