首页 > 解决方案 > 在为地理空间查询定义索引后显示“IndexNotFound”错误

问题描述

我定义的索引:

tourSchema.index( {startLocation: "2dsphere"} );

获取距离的控制器功能是:

exports.getDistances = catchAsync(async (req, res, next) => {

  const { latlng, unit } = req.params;
 
  const [lat, lng] = latlng.split(',');

  const multiplier = unit === 'mi' ? 0.000621371 : 0.001;

  if(!lat || !lng){
    next(new AppError('Please provide latitude and longitude in the format lat, lng.', 400));
  }
  
  const distances = await Tour.aggregate([
    {
      $geoNear: {
        near: {
          type: 'Point',
          coordinates: [lng * 1, lat * 1]
        },
        distanceField: 'distance',
        distanceMultiplier: multiplier     
      }
    },
    {
      $project: {
        distance: 1,
        name: 1
      }
    }
  ]);
  
  res.status(200).json({
    status: 'Success',
    data: {
      data: distances
    }
  });
});

我使用的路线是:

const router = express.Router();


router.route('/distances/:latlng/unit/:unit').get(tourController.getDistances);

我得到的错误:

{“状态”:“错误”,“错误”:{“操作时间”:“6963883450025639937”,“确定”:0,“代码”:27,“代码名称”:“IndexNotFound”,“$clusterTime”:{“clusterTime” ": "6963883450025639937", "签名": { "hash": "IhmwbnoiKdpWvx5rhQv2nnzmYiM=", "keyId": "6905064895109136388" } }, "name": "MongoError", "statusCode": 500, "status": "error " },

"message": "$geoNear 需要 2d 或 2dsphere 索引,但没有找到",

标签: javascriptmongodb

解决方案


推荐阅读