首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongoose无法识别我的2dsphere索引

Mongoose无法识别我的2dsphere索引
EN

Stack Overflow用户
提问于 2020-02-10 01:16:06
回答 1查看 422关注 0票数 0

我正在尝试为我的字段添加2dSphere索引startLocation exists in tourSchema。下面是它在下面的样子

代码语言:javascript
复制
   startLocation: {
      type: {
        type: String,
        default: 'Point',
        enum: ['Point']
      },
      coordinates: [Number],
      address: String,
      description: String
    }

您还可以在下面看到我在此模式上添加了什么索引以及如何添加索引

代码语言:javascript
复制
tourSchema.index({price:1,ratingsAverage:-1});
tourSchema.index({slug:1});
tourSchema.index({ startLocation: '2dsphere' });

不幸的是,Mongodb不能识别startLocation索引。使用Mongo Compass,我可以看到除了startLocation:'2dsphere'.之外我创建的所有索引

当我向控制器中的getDistances方法发送请求时,postman给我的错误如下:

代码语言:javascript
复制
{
    "status": "error",
    "error": {
        "operationTime": "6791492473605586945",
        "ok": 0,
        "errmsg": "$geoNear requires a 2d or 2dsphere index, but none were found",
        "code": 27,
        "codeName": "IndexNotFound",
        "$clusterTime": {
            "clusterTime": "6791492473605586945",
            "signature": {
                "hash": "4LYCSBslSoLAoqj93bLXmpubBxs=",
                "keyId": "6779443539857113090"
            }
        },
        "name": "MongoError",
        "statusCode": 500,
        "status": "error"
    },
    "message": "$geoNear requires a 2d or 2dsphere index, but none were found",
    "stack": "MongoError: $geoNear requires a 2d or 2dsphere index, but none were found\n    at Connection.<anonymous> (C:\\Users\\timuc\\Downloads\\starter\\starter\\node_modules\\mongodb-core\\lib\\connection\\pool.js:443:61)\n    at Connection.emit (events.js:223:5)\n    at processMessage (C:\\Users\\timuc\\Downloads\\starter\\starter\\node_modules\\mongodb-core\\lib\\connection\\connection.js:364:10)\n    at TLSSocket.<anonymous> (C:\\Users\\timuc\\Downloads\\starter\\starter\\node_modules\\mongodb-core\\lib\\connection\\connection.js:533:15)\n    at TLSSocket.emit (events.js:223:5)\n    at addChunk (_stream_readable.js:309:12)\n    at readableAddChunk (_stream_readable.js:290:11)\n    at TLSSocket.Readable.push (_stream_readable.js:224:10)\n    at TLSWrap.onStreamRead (internal/stream_base_commons.js:181:23)"
}

我尝试添加被mongodb识别的point: '2dsphere',但我不满意。因为当我向控制器中的方法发送请求时,会返回成功,但返回的数组为空数组。

下面是在控制器中触发的方法:

代码语言:javascript
复制
exports.getDistances = catchAsync(async (req, res, next) => {
  const { latlng, unit } = req.params;
  const [lat, lng] = latlng.split(",");
  if (!lat || !lng) {
    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"
      }
    }
  ]);

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

您还可以从路由器上看到我是如何发送下面的请求URL的

代码语言:javascript
复制
tourRouter.route('/distances/:latlng/unit/:unit').get(tourController.getDistances);
EN

回答 1

Stack Overflow用户

发布于 2020-02-10 02:31:45

我强烈地认为您没有使用正确的集合。这适用于MongoDB 4.2。

创建索引:

代码语言:javascript
复制
db.location.createIndex({
    startLocation: "2dsphere"
})

该集合的索引:

代码语言:javascript
复制
db.location.getIndexes()
[{
        "v": 2,
        "key": {
            "_id": 1
        },
        "name": "_id_",
        "ns": "stackoverflow.location"
    }, {
        "v": 2,
        "key": {
            "startLocation": "2dsphere"
        },
        "name": "startLocation_2dsphere",
        "ns": "stackoverflow.location",
        "2dsphereIndexVersion": 3
    }
]

插入一些数据:

代码语言:javascript
复制
db.location.insert({
    startLocation: {
        type: "Point",
        coordinates: [40, 5],
        address: "Hellostreet 1",
        description: "Hello"
    }
})

聚合集合:

代码语言:javascript
复制
db.location.aggregate([{
        $geoNear: {
            near: {
                type: 'Point',
                coordinates: [41, 6]
            },
            distanceField: 'distance'
        }
    }
])

结果是:

代码语言:javascript
复制
{
    "_id" : ObjectId("5e404cdd13552bde0a0a9dc5"),
    "startLocation" : {
            "type" : "Point",
            "coordinates" : [
                    40,
                    5
            ],
            "address" : "Hellostreet 1",
            "description" : "Hello"
    },
    "distance" : 157065.62445348964
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60139209

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档