2

Add schema.index({startlocation: '2dsphere'}) in schema but not able to clear the error. schema tourSchema.index({ startLocation: '2dsphere' }); --> this line is add in model

controller

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

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

if (!lat || !lng) {
next(
  new AppError(
    'Please provide latitutr and longitude in the format lat,lng.',
    400
  )
);
}
const distances = await Tour.aggregate([
{
  $geoNear: {
    near: {
      type: 'Point',
      coordinates: [lng * 1, lat * 1],
    },
    distanceField: 'distance',
    distanceMultiplier: multiplier,
    spherical: true,
  },
},
{
  $project: {
    distance: 1,
    name: 1,
  },
},
]);

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

"error": "message": "$geoNear requires a 2d or 2dsphere index, but none were found",

I am getting this error, please help me out with this. Thanks In Advance

singu
  • 21
  • 1
  • 4

4 Answers4

1

Looks like you're watching Jona's node Course. I had the same problem. You should go back to MongoDb Compass, remove the index, and then copy this code:

tourSchema.index({
    startLocation: "2dsphere",
})

Then restart the server and check in MongoDb Compass that your index is GEOSPATIAL. After that, it will work.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
1

I followed the same course and got the same issue. Adding the index manually in mongoDB gave me some insight

> db.tours.createIndex({ startLocation: "2dsphere" })
{
    "ok" : 0,
    "errmsg" : "Index build failed: daf8a8c6-a580-4913-8732-5fbb7b5641b0: Collection natours.tours ( 4840d817-5cdb-4d5e-91ff-543cd26824ad ) :: caused by :: Can't extract geo keys: { _id: ObjectId('61542fdbbab94c9f1075336d'), startLocation: { type: \"Point\", coordinates: [] }, ratingsAverage: 4.8, ratingsQuantity: 1, images: [], createdAt: new Date(1632907215605), startDates: [], secretTour: false, guides: [], name: \"New Test Tour\", duration: 5, maxGroupSize: 25, difficulty: \"easy\", price: 397, summary: \"Breathtaking hike through the Canadian Banff National Park\", imageCover: \"tour-1-cover.jpg\", location: [], slug: \"new-test-tour\", __v: 0 }  Point must only contain numeric elements",
    "code" : 16755,
    "codeName" : "Location16755"
}

In this case, I've created a tour without any coordinates and the 2dsphere index couldn't be created. Removing this wrongfully tour solved the issue.

Ting Lee
  • 21
  • 2
0

if none of this works then you can simply go to mongodb compass and follow these below steps:

  1. go to your tours
  2. and on index section
  3. click on create an index fill the popup create index as on below image

https://i.stack.imgur.com/UijAG.png

Monjiro
  • 11
  • 2
0
  1. Make sure that all the tours in the mongodb have geolocation data that will be used when calculating distances.
  2. If the error persist add the startLoction index directly from the mongodb compass. Demo
PcodesDev
  • 1
  • 1
  • 3