【问题标题】:$geoNear requires a 2d or 2dsphere index, but none were found$geoNear 需要 2d 或 2dsphere 索引,但没有找到
【发布时间】:2020-05-02 14:22:42
【问题描述】:

在架构中添加 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 索引,但没有找到",

我收到此错误,请帮助我解决此问题。 提前致谢

【问题讨论】:

    标签: node.js mongoose mongodb-indexes


    【解决方案1】:

    我遵循相同的课程并遇到相同的问题。在 mongoDB 中手动添加索引给了我一些见解

    > db.tours.createIndex({ startLocation: "2dsphere" })
    
    {
        "ok" : 0,
        "errmsg" : "Index build failed: daf8a8c6-a580-4913-8732-5fbb7b5641b0: Collection natours.tours ( 4840d817-5cdb-4d5e-91ff-543cd26824ad ) :: caused by :: Can't extract geo keys: { _id: ObjectId('61542fdbbab94c9f1075336d'), startLocation: { type: \"Point\", coordinates: [] }, ratingsAverage: 4.8, ratingsQuantity: 1, images: [], createdAt: new Date(1632907215605), startDates: [], secretTour: false, guides: [], name: \"New Test Tour\", duration: 5, maxGroupSize: 25, difficulty: \"easy\", price: 397, summary: \"Breathtaking hike through the Canadian Banff National Park\", imageCover: \"tour-1-cover.jpg\", location: [], slug: \"new-test-tour\", __v: 0 }  Point must only contain numeric elements",
        "code" : 16755,
        "codeName" : "Location16755"
    }
    

    在这种情况下,我创建了一个没有任何坐标的游览,并且无法创建 2dsphere 索引。删除这个错误的游览解决了这个问题。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-13
        • 2014-06-27
        • 2016-09-30
        • 2017-03-24
        • 2018-10-28
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        相关资源
        最近更新 更多