【问题标题】:Mongoose query on GeoJSON objects对 GeoJSON 对象的 Mongoose 查询
【发布时间】: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


    【解决方案1】:

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

    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')})
          }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-14
      • 2021-08-31
      • 2013-06-03
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多