$ geoNear需要2d或2dsphere索引,但未找到

时间:2020-05-02 14:22:42

标签: node.js mongoose mongodb-indexes

在架构中添加schema.index({startlocation:'2dsphere'}),但无法清除错误。 图式 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 latitutr 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,
    spherical: true,
  },
},
{
  $project: {
    distance: 1,
    name: 1,
  },
},
]);

 res.status(200).json({
 status: 'success',
 data: {
  data: distances,
 },
 });
 });

“错误”: “ message”:“ $ geoNear需要2d或2dsphere索引,但没有找到”“

我遇到此错误,请帮我解决这个问题。 在此先感谢

1 个答案:

答案 0 :(得分:0)

好像您正在看Jona的节点课程。我有同样的问题。您应该回到MongoDb Compass,删除索引,然后复制以下代码:

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

然后重新启动服务器,并在MongoDb Compass中检查您的索引为GEOSPATIAL。之后,它将起作用。

相关问题