0

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

{
   ...
   "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”是未定义的。

我究竟做错了什么?

4

1 回答 1

0

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

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')})
      }
于 2021-04-27T09:40:53.977 回答