对 GeoJSON 对象的 Mongoose 查询

问题描述

我试图查询一些按到某个位置(用户位置)的距离排序的餐厅。 我有一个“餐厅”集合,其中包含如下文档:

{
   ...
   "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)

在这个集合上,我定义了以下索引:

enter image description here

在我的 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”是未定义的。

我做错了什么?

解决方法

我太笨了。 一切正常,只是回调没有得到正确的变量。将我的功能更改为此解决了问题:

if(req.headers.lng && req.headers.lat){
        var restaurants = await Restaurant.find({
            location: {
                $near: {
                    $geometry: {
                        type : "Point",coordinates : [parseFloat(req.headers.lng),parseFloat(req.headers.lat)]
                    },$maxDistance: 50000
                }
            }
        });
        console.log(restaurants);
      }else{
          return res.json({success: false,msg: res.__('invalidArgumentsErrorMsg')})
      }