猫鼬地理位置动态最大距离

时间:2019-07-06 15:49:04

标签: node.js mongodb

当前,我正在使用MongoDB,并且具有以下模式的用户集合:

const DEFAULT_JOB_RADIUS = 5000 // In meters

const settingsSchema = new Schema({
  jobRadius: {
    type: Number,
    default: DEFAULT_JOB_RADIUS
  }
})

const userSchema = new Schema({
  firstName: {
    trim: true,
    type: String
  },
  lastName: {
    trim: true,
    type: String
  },
  email: {
    trim: true,
    type: String,
    unique: true
  },
  password: {
    type: String
  },
  token: {
    type: String
  },
  fcmToken: {
    type: String
  },
  lastLocation: {
    type: pointSchema
  },
  settings: {
    type: settingsSchema,
    default: settingsSchema
  }
}, {
  timestamps: true
})

点模式如下:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const pointSchema = new Schema({
  type: {
    type: String,
    enum: ['Point'],
    default: 'Point'
  },
  coordinates: {
    type: [Number],
    default: [0, 0],
    index: '2dsphere'
  }
});

module.exports = pointSchema

每个用户都有一个jobRadius属性。此属性表示用户到任何点的最大距离。

在我的代码中,我需要获取特定点附近的所有用户。 这是我目前正在尝试做的事情:

async getNearbyUsers(point) {
    const users = await this.model.aggregate([
      {
        $geoNear: {
          near: point,
          distanceField: "dist.calculated",
          maxDistance: '$settings.jobRadius',
          spherical: true
        }
      }
    ])

    return users
  }

此代码无效。它总是带给我所有用户。 如果我将maxDistance字段更改为类似的内容,它将起作用:

maxDistance: 1

我的问题是-在最大距离是动态的且特定于每个用户的情况下,如何执行这种聚合?

1 个答案:

答案 0 :(得分:0)

好,所以我设法在@Ashh的帮助下解决了这个问题 首先计算用户与点之间的距离,然后过滤所有用户的半径属性超过该距离的用户。

async getNearbyUsers(point) {
    const users = await this.model.aggregate([
      {
        $geoNear: {
          near: point,
          distanceField: "dist.calculated",
          spherical: true
        }
      },
      {
        $match: {
          $expr: {
            $gt: ['$settings.jobRadius', '$dist.calculated']
          }
        }
      }
    ])

    return users
  }