singu
singu

Reputation: 31

$geoNear requires a 2d or 2dsphere index, but none were found

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

Upvotes: 3

Views: 5407

Answers (8)

Vamshi
Vamshi

Reputation: 1

Delete the test tour you have created Now it will run without any errors

The issue is with your test tour, it has no coordinates so it is giving index build error

Upvotes: 0

Israr Rashid
Israr Rashid

Reputation: 1

Try to make a some requests after login, like "Get Tour", "Get All Tours", when make these requests your tourModel file will also executed with it, then it will add the startLocation index in database indexes tab.

Upvotes: 0

Viktor Kyporenko
Viktor Kyporenko

Reputation: 1

  • I faced with the same error and fixed it by removing all tours
    (documents) with empty locations from DB. It will unblocks DB to set index properly.
  • After deleting index will be set automatically with restarting app (server).

Upvotes: 0

Khushal Ahir 2
Khushal Ahir 2

Reputation: 1

The reason behind this error is actually Jonas provided us a pre build data of tours, in all that data there are a location field which is not empty generally this error is occurs when your location field is empty array make sure that your location array is not empty and please try to work with Jonas's provided tours data do not add your own tour and if you add your own tour make sure your location array should not be empty otherwise you will face this error even you added index in your tour model.

Upvotes: 0

PcodesDev
PcodesDev

Reputation: 36

  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

Upvotes: 0

Monjiro
Monjiro

Reputation: 11

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.sstatic.net/UijAG.png

Upvotes: 0

Ting Lee
Ting Lee

Reputation: 21

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.

Upvotes: 1

Yasser Goumghar
Yasser Goumghar

Reputation: 69

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.

Upvotes: 4

Related Questions