当使用mongoosegeoNear()不能按预期工作

我使用mongodb和mongoose作为我的应用的ODM。 我有一个文件,拿着一家餐馆的位置。 模型(模式)是这样的:

var locationSchema = new mongoose.Schema({ name: {type:String, required:true}, address: String, coords: {type:[Number], index:'2dsphere', required:true}, }); 

这里是我的样本数据:

  "_id" : ObjectId("56b39d9673ff055a098dee71"), "name" : "Holycow STEAKHOUSE", "address" : "somewhere", "coords" : [ 106.7999044, -6.2916982 ] 

然后,我使用mongoose从餐馆约2公里内的某个地方得到餐厅的位置。 我从mongodb文件读取,我们必须提供maxDistance参数的辐射和distanceMultiplier与地球半径,所以我把下面的代码到我的控制器:

 var point = { type: "Point", coordinates: [106.8047355, -6.2875187] // the test data, approximately 2 km from the restaurant } var geoOptions = { spherical: true, num: 10, maxDistance: 5 / 6371 , // i set maximum distance to 5 km. to make sure I found the place. distanceMultiplier: 6371 } Loc.geoNear(point, geoOptions, function(err, results, stats){ var locations = []; if(err){ console.log(err); sendJsonResponse(res, 404, err); } else { results.forEach(function(doc){ locations.push({ distance: doc.dis, name: doc.obj.name, address: doc.obj.address, _id: doc.obj._id }); }); sendJsonResponse(res, 200, locations); } }); 

但没有find餐厅。 我已经阅读了两个小时的文档,但仍然没有线索。 我的代码有什么问题?

尝试这个:

 var geoOptions = { spherical: true, num: 10, maxDistance: 5 * 1000 , // Convert kilometers to meters } 

我想我们正在读同一本书。 你的代码很熟悉,而且我也遇到了同样的问题。

您的代码无法正常工作,因为您认为maxDistace正在使用单位弧度。 但是,不, naxDistance使用米。 您还需要删除distanceMultiplier因为它会将您的maxDistance转换为弧度,这不是正确的单位。

试试这个链接: MongoDB Docs $ maxDistance