MongoDB: $geoNear aggregation returns an empty array

Viewed 11

I'm following a Mongoose tutorial I did everything as the tutor did, but I get an empty array when I use $geoNear aggregation.

The request handler

exports.getDistances = catchAsync(async (req, res, next) => {
  const { latlang, unit } = req.params;
  const [lat, lang] = latlang.split(',');

  const multiplier = unit === 'mi' ? 0.000621371 : 0.001

  if (!lat || !lang) {
    next(
      new AppError(
        'Please provide latitude and longitude in format: lat,lang',
        400
      )
    );
  }

  const distances = await Tour.aggregate([
    {
      $geoNear: {
         near: {type: "Point", coordinates: [lang * 1, lat * 1  ]}  ,
         distanceField: "distance",
         distanceMultiplier: multiplier 
      },
      $project: {
        distance: 1,
        name: 1
      }
    }
  ])

  res.status(200).json({
    status: 'success',
    results: distances.length,
    data: {
      data: distances,
    },
  });
});

And here is the index

tourSchema.index({startLoaction: '2dsphere'})

Although the aggregation doesn't work even using MongoDB compass

0 Answers
Related