【发布时间】:2021-04-27 17:40:53
【问题描述】:
我正在尝试查询一些按其到某个位置(用户位置)的距离排序的餐厅。 我有一个“餐厅”集合,其中包含如下文件:
{
...
"location": {
"type": "Point",
"coordinates": [7.756894, 45.093654]
},
...
}
我的 Mongoose 架构如下所示:
const restaurantSchema = new mongoose.Schema({
...
location: {
type: {
type: String,
enum: ['Point'],
required: true
},
coordinates: {
type: [Number],
required: true
}
},
...
});
restaurantSchema.index({location: '2dsphere'});
module.exports = mongoose.model('Restaurant', restaurantSchema)
在这个集合上我定义了以下索引:
在我的 nodejs 服务器中,我有以下函数尝试检索用户当前位置附近的餐馆(按距离排序)(在请求标头中收到):
getRestaurantsNearYou: function(req, res){
if(req.headers.lng && req.headers.lat){
Restaurant.find({
location: {
$near: {
$geometry: {
type : "Point",
coordinates : [parseFloat(req.headers.lng), parseFloat(req.headers.lat)]
},
$maxDistance: 5000
}
}
}).then(function(err, restaurants){
console.log(restaurants);
return res.json({success: true, restaurants: restaurants});
}).catch(err=>{if(err) throw err;});
}else{
return res.json({success: false, msg: res.__('invalidArgumentsErrorMsg')})
}
}
这段代码没有错误,但是这个函数的返回只是
{
success: true
}
我试图返回的变量“restaurants”是未定义的。
我做错了什么?
【问题讨论】:
标签: mongoose mongodb-query geojson mongoose-schema mongodb-geospatial