Node.js Mongodb和nodejs geonear响应更改位置?

Node.js Mongodb和nodejs geonear响应更改位置?,node.js,mongodb,Node.js,Mongodb,在我的nodejs应用程序中,我查询mongodb以输出给定地址周围100公里处的用户 以下是一种文档类型: { "_id" : ObjectId("5b26192e01e60e1e67e37b50"), "loc":[2.4066412, 48.8599825] .... } 以及nodejs查询: const distance = "100000"; User.aggregate([{ $geoNear: { near: {type: "

在我的nodejs应用程序中,我查询mongodb以输出给定地址周围100公里处的用户

以下是一种文档类型:

{ 
    "_id" : ObjectId("5b26192e01e60e1e67e37b50"), 
    "loc":[2.4066412, 48.8599825]
    ....
}
以及nodejs查询:

const distance = "100000";
User.aggregate([{
    $geoNear: {
        near: {type: "Point", coordinates: [ latitude, longitude ]},
        distanceField: "loc",
        minDistance:0,
        maxDistance:distance,
        spherical: true
    }
}], function(err, resp){
    console.log(resp)
})
此代码运行良好,我可以输出指定距离附近的用户,但响应对象位置已更改:

{ 
    "_id" : ObjectId("5b26192e01e60e1e67e37b50"), 
    "loc": "5419.825102233618" // <=== WHY IT DOESN'T RETURN RIGHT DATA ?
    ....
}
但是:

谢谢。

在地理空间索引上工作,而不是直接在字段上工作,我想这就是为什么它可能会令人困惑的原因。这意味着在运行
$geoNear
之前,必须创建如下索引:

db.col.ensureIndex({ loc: "2dsphere" })
这是唯一指定
loc
作为
$geoNear
输入的地方。然后,当您使用
distance字段:“loc”
时,您定义希望在
loc
字段中获得计算的距离,该字段仅覆盖您的坐标

因此,要从源文档获取距离和坐标,您应该将距离字段定义为不同的键,例如:

db.col.aggregate([{
    $geoNear: {
        near: {type: "Point", coordinates: [2.4066412, 48.8599825]},
        distanceField: "distance",
        minDistance:0,
        maxDistance: 10000,
        spherical: true
    }
}])
然后你会得到:

{ "_id" : ObjectId("5b26192e01e60e1e67e37b50"), "loc" : [ 2.4066412, 48.8599825 ], "distance" : 0 }

您好,谢谢您的回复,让我更干净,我会尝试一下,我刚刚尝试了您的建议,工作取得了成功。非常感谢。
db.col.aggregate([{
    $geoNear: {
        near: {type: "Point", coordinates: [2.4066412, 48.8599825]},
        distanceField: "distance",
        minDistance:0,
        maxDistance: 10000,
        spherical: true
    }
}])
{ "_id" : ObjectId("5b26192e01e60e1e67e37b50"), "loc" : [ 2.4066412, 48.8599825 ], "distance" : 0 }