0

I have this schema in mongoose:

new Schema({
    location: {
        type: {
            type: String,
            enum: ['Point']
        },
        coordinates: {
            type: [Number],
            index: '2dsphere'
        }
    }
})

I want to sort base on distance from supplied lng and lat. I'm just learning mongoose so I ran into an issue I'm getting this error when trying to sort:

unable to find index for $geoNear query

This is what I've tried (in this case lat and lng are 1):

const banners = await FullBanner
        .where('location')
        .near({
            center: {
                type: 'Point',
                coordinates: [1, 1]
            },
            maxDistance: 10 * 1000
        })
        .exec();

const banners = await FullBanner
        .where('location')
        .near({ center: [1, 1] });

const banners = await FullBanner
        .find({})
        .where('location')
        .near({ center: [1, 1] });

const banners = await FullBanner.find({
        location: {
            $near: {
                $geometry:{
                    type: "Point",
                    coordinates: [1, 1]
                }
            }
        }
    });

This is like in the example at their official website: https://mongoosejs.com/docs/api.html#query_Query-near Can someone explain what I'm doing wrong and what is a proper way to sort my schema based on distance

Misho Tek
  • 624
  • 2
  • 11
  • 22
  • Check out this answer [stackoverflow](https://stackoverflow.com/a/23189240/10310278) I think that will help you – cvekaso May 09 '20 at 19:42
  • @salesh I've seen this question, but I think I have a different issue. I have specified index of type 2dsphere and the answer to that question is for mongodb not mongoose, I have a hard time trying to convert one query to another – Misho Tek May 09 '20 at 19:55
  • did you create in schema index like this FullBannerSchema.index({ location: '2dsphere' }); ? – cvekaso May 09 '20 at 20:01
  • I thought that `coordinates: { type: [Number], index: '2dsphere' }` was doing this, I've added that line and everything works now – Misho Tek May 09 '20 at 20:04
  • 1
    @salesh could you post it as an answer so that I can accept it? – Misho Tek May 09 '20 at 20:04

1 Answers1

1

So, in this case, solution is to:

Create index in schema like this FullBannerSchema.index({ location: '2dsphere' });

You were on the right path, just configuration was slightly different :)

cvekaso
  • 833
  • 1
  • 11
  • 28