首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用循环对数据进行排序,以查找离用户最近的餐厅

使用循环对数据进行排序,以查找离用户最近的餐厅
EN

Stack Overflow用户
提问于 2021-09-09 04:20:34
回答 1查看 70关注 0票数 0

我将餐厅的地理坐标存储在MongoDB数据库中。

现在,我需要创建一个循环来获取所有餐馆的地理坐标和用户地理坐标,以获得最近的5家餐馆。我不知道如何循环和匹配用户的地理坐标。

我想要恰好有5家餐厅在我附近,因为Google place API集成在前端,所以我只能获得我需要匹配的地理坐标,以便在我附近获得确切的餐厅。

代码语言:javascript
复制
nearby_restro: (req, res) => {var user_id = req.user;var reqdata = req.body;var lat = reqdata.lat;
var long = reqdata.long; 
 locationModel.find({
"loc": {$near: [longitude = long, latitude = lat]}}, (err, data) => {console.log(err)
console.log(data)})
model 
   userId :{  type: mongoose.Schema.Types.ObjectId, required: true, auto: true},
    loc: {
      type: {
        type: String, // Don't do `{ location: { type: String } }`
        enum: ['Point'], // 'location.type' must be 'Point'
      },
      cordinates:[{
        longitude:{type:String },
        latitude:{type:String },
      }],

我希望通过使用restro和用户在long和lat中的坐标来获得用户的所有附近餐厅。我使用的是用户坐标,但这个查询对我不起作用。

EN

回答 1

Stack Overflow用户

发布于 2021-09-10 07:44:39

MongoDB地理空间使用geoJSON。下面是模式应该是什么样子。请注意,geo字段是使用2dsphere建立索引的。

代码语言:javascript
复制
const productSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  geo: {
    type: {
      type: String, // Don't do `{ location: { type: String } }`
      enum: ['Point'], // 'location.type' must be 'Point'
      default: 'Point',
    },
    coordinates: [
      { type: Number },
    ],
  },
}, { timestamps: true });

productSchema.index({ geo: '2dsphere', name: 'text' });

要查询产品集合,我们将使用MongoDB $geoNear查询

代码语言:javascript
复制
const products = ProductModel.aggregate([
    {
      $geoNear: {
        near: { type: 'Point', coordinates: [<lat>, <lng>] },
        key: 'geo',
        distanceField: 'dist.calculated',
        spherical: true,
      },
    },
    { $limit: 10 },
  ]);

distanceField将返回一个数字,显示项目和传递的坐标之间的距离。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69112197

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档