1

我正在尝试从特定点获取附近位置的结果。通过使用按 ID 查找的常规方式,返回了一个结果,但是当我尝试使用坐标查找附近的位置时,没有出现任何结果。我的代码中没有任何错误/警告,但也没有任何结果。我错过了什么?

模型架构

var locationSchema = new Schema({
    fb_location: String,
    coordinates:[]
});

var feed_postSchema = new Schema({
    content: String,
    location: [locationSchema],
    image: [{ type : String }],
    created_at: { type : Date, default: Date.now }
});

locationSchema.index({coordinates:'2dsphere'});

服务器.js

app.get('/test_radar',function(request,response){
    Feed_Post.find( 
    {
        'location.coordinates' :
        {
            $near : 
            {
                coordinates: [100,5]
            },
            $maxDistance: 100
        }
    },function(err,ret){
        console.log(response.json(ret));
    })
});

示例数据库数据

    "_id" : ObjectId("5620a3c2fde01a55065f4c3b"),
    "content" : "Test post",
    "created_at" : ISODate("2015-10-16T07:14:10.636Z"),
    "image" : [ ],
    "location" : [
            {
                    "fb_location" : "Malaysia",
                    "_id" : ObjectId("5620a3c2fde01a55065f4c3c"),
                    "coordinates" : [
                            100,
                            5
                    ]
            }
    ],
    "__v" : 0

注意:我确实将 $maxDistance 设置为 100 * 1000。仍然没有结果。

4

1 回答 1

1

$near运算符需要地理空间索引。

如果您想使用旧坐标将您的位置定义为一个点,您必须创建 2D 索引。然后您将能够$near在您指定的语法中使用运算符。

您创建了 2dsphere 索引,因此您必须在查询中指定 GeoJSON 点:

Feed_Post.find( 
    {
        'location.coordinates' :
        {
            $geometry: {
                 type: "Point" ,
                 coordinates: [ 100 , 5 ]
            },
            $maxDistance: 100
        }
    },function(err,ret){
        console.log(response.json(ret));
    })

检查$near定义。

于 2015-10-16T09:04:56.957 回答