Mongoose排序与near和geoson
我在mongoose中有这样的模式:Mongoose排序与near和geoson,mongoose,Mongoose,我在mongoose中有这样的模式: new Schema({ location: { type: { type: String, enum: ['Point'] }, coordinates: { type: [Number], index: '2dsphere' } } }) 我想根据供应lng和lat的距离进行排序
new Schema({
location: {
type: {
type: String,
enum: ['Point']
},
coordinates: {
type: [Number],
index: '2dsphere'
}
}
})
我想根据供应lng和lat的距离进行排序。我只是在学习mongoose,所以我遇到了一个问题,在尝试排序时出现了以下错误:
找不到$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]
}
}
}
});
这与他们官方网站上的示例类似:
有人能解释一下我做错了什么,以及什么是基于距离对模式排序的正确方法吗?因此,在这种情况下,解决方案是: 在模式中创建索引,如FullBannerSchema.index{location:'2dsphere'}
您走的路是对的,只是配置略有不同:看看这个答案,我认为这会有所帮助you@salesh我见过这个问题,但我想我有一个不同的问题。我已经指定了2dsphere类型的索引,这个问题的答案是对于mongodb而不是mongoose,我很难将一个查询转换为另一个查询。您是否在类似FullBannerSchema的模式索引中创建了索引{location:'2dsphere'}?我以为坐标:{type:[Number],index:'2dsphere'}就是这么做的,我添加了那行,一切都正常now@salesh你能把它作为答案贴出来让我接受吗?