猫鼬与近距离和GeoJson排序

时间:2020-05-09 19:37:22

标签: mongoose

我的猫鼬有这个模式:

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

我想根据距提供的lng和lat的距离进行排序。我只是在学习猫鼬,所以遇到一个问题,在尝试排序时遇到此错误:

找不到$ geoNear查询的索引

这是我尝试过的方法(本例中lat和lng为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]
                }
            }
        }
    });

这就像他们的官方网站上的示例:https://mongoosejs.com/docs/api.html#query_Query-near 有人可以解释我做错了什么,以及根据距离对我的架构进行排序的正确方法是什么

1 个答案:

答案 0 :(得分:1)

因此,在这种情况下,解决方案是:

在诸如FullBannerSchema.index({location:'2dsphere'})这样的架构中创建索引;

您走在正确的道路上,只是配置略有不同:)