无法使用Mongoose / MongoDB中的coordinate $ near语句查找附近位置的结果

时间:2015-10-16 07:52:04

标签: node.js mongodb mongoose mongoose-populate

我正在尝试从特定点获取附近位置的结果。通过使用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'});

Server.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.仍然没有结果。

1 个答案:

答案 0 :(得分:1)

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

如果您想使用旧版坐标将您的位置定义为一个点,则必须2D index created。然后,您将能够在指定的语法中使用$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定义。