在猫鼬10英里半径范围内针对我的坐标查找附近的用户

时间:2019-05-02 13:34:24

标签: node.js mongodb mongoose

我正面临MongoDB的MongoDB地理空间查询问题。我有一个具有以下架构的用户文档。并且我希望所有用户在10英里之内,例如:如果我的坐标是[77.07361279999999,28.4770304],那么我希望所有用户在半径10英里之内

我正在遵循此文档: link

const pointSchema = {
  PointType: {
    type: String,
    enum: ['Point'],
    required: true
  },
  coordinates: {
    type: [Number],
    required:true
  }
};

let userFields = {
  userName: {
    type: String,
    index: true,
    unique: true,
    required: true,
    lowercase: true,
  },
  gender: {
    type: String,
    enum: ['male', 'female']
  },
  currentLocation: {
    type: pointSchema,
    index: true,
    unique: true,
  }
};

let userSchema = new SCHEMA(Object.assign({}, userFields), { runSettersOnQuery: true });
let userModel = MONGOOSE.model('User', userSchema);

我的查询是:

let recommendationList = userModel.find({
  currentLocation: {
    $nearSphere: {
      $geometry: {
        type: 'Point',
        coordinates: [77.07361279999999, 28.4770304],
      },
      $maxDistance: 10
    }
  }
});

1 个答案:

答案 0 :(得分:1)

因此,在正确阅读了文档here之后,我终于弄清了您在做什么错,几乎没有错。

您需要将架构更改为

const pointSchema = {
      type: {
        type: String,
        enum: ['Point'],
        required: true
      },
      coordinates: {
        type: [Number],
        required:true
      }
    };

并向模型添加sureIndexes

userModel.ensureIndexes({ 'currentLocation': '2dsphere' });

最后在控制器中,您应该像这样查询模型

let recommendationList = await userModel.aggregate([
      {
        $geoNear: {
          near: {
            type: 'Point',
            coordinates: userObj.currentLocation.coordinates
          },
          spherical: true,
          maxDistance: 10 * 1609.34,
          distanceMultiplier: 1,
          distanceField: 'distance',
          limit: 1,
          query : {
            gender: userObj.userPreference.datingPreferenceGender
          }
        }
      }
    ]);