Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/457.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 猫鼬罐头';我不认识我的2dsphere索引_Javascript_Node.js_Mongodb_Mongoose - Fatal编程技术网

Javascript 猫鼬罐头';我不认识我的2dsphere索引

Javascript 猫鼬罐头';我不认识我的2dsphere索引,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我正在尝试为我的字段添加2dSphere索引startLocation存在于tourSchema中。下面是它的样子 startLocation: { type: { type: String, default: 'Point', enum: ['Point'] }, coordinates: [Number], address: String, description: String

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

   startLocation: {
      type: {
        type: String,
        default: 'Point',
        enum: ['Point']
      },
      coordinates: [Number],
      address: String,
      description: String
    }
您还可以在下面看到我在这个模式上添加了什么以及如何添加索引

tourSchema.index({price:1,ratingsAverage:-1});
tourSchema.index({slug:1});
tourSchema.index({ startLocation: '2dsphere' });
不幸的是,
Mongodb
无法识别
startLocation
索引。使用
Mongo Compass
,我可以看到我创建的所有索引,除了
startLocation:'2dsphere'。

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

{
    "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)"
}
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

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

我坚信您没有使用正确的收藏。这适用于MongoDB 4.2

创建索引:

db.location.createIndex({
    startLocation: "2dsphere"
})
该集合的索引:

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
    }
]
db.location.aggregate([{
        $geoNear: {
            near: {
                type: 'Point',
                coordinates: [41, 6]
            },
            distanceField: 'distance'
        }
    }
])
插入一些数据:

db.location.insert({
    startLocation: {
        type: "Point",
        coordinates: [40, 5],
        address: "Hellostreet 1",
        description: "Hello"
    }
})
集合集合:

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
    }
]
db.location.aggregate([{
        $geoNear: {
            near: {
                type: 'Point',
                coordinates: [41, 6]
            },
            distanceField: 'distance'
        }
    }
])
结果是:

{
    "_id" : ObjectId("5e404cdd13552bde0a0a9dc5"),
    "startLocation" : {
            "type" : "Point",
            "coordinates" : [
                    40,
                    5
            ],
            "address" : "Hellostreet 1",
            "description" : "Hello"
    },
    "distance" : 157065.62445348964
}

您的巡更对象是否指向正确的集合,因为根据您的输入,这在我的端正常工作。(MongoDB 4.2)此链接可供您详细使用。你解决你的问题了吗?谢谢你的回答,但我正在使用mongoose处理NodeJ。所以我应该使用schema而不是db.location.createIndex.should schema.Index…你也可以查看我的项目,了解关于这个repo@Timuçinçek的更多详细信息。手动创建索引没有错。实际上,即使在mongoose文档中,他们也声明mongoose不是索引管理解决方案。很明显,mongoose无法创建索引,您需要自己创建索引。