geoNear异常:'near'字段必须是一个点。

5

我已经在mongo shell中成功运行了以下查询:

db.runCommand({
    geoNear : "stores",
    near : { type : "Point", coordinates : [ -3.978, 50.777 ] },
    spherical : true,
    limit : 10
})

我正试图将此转换为我的 Node 服务中的 Mongoose 查询 如文档中所示

Store.geoNear(
    { type : "Point", coordinates : [-3.978, 50.777]}, 
    { spherical : true, limit : 10 }, 
    function (error, results, stats) {
    //do stuff with results here
});

这里返回以下错误:
MongoError: exception: 'near' field must be point

我的Store架构定义如下:

var storeSchema = new Schema({
    // irrelevant fields...
    locations : [
        {
            address : {
                streetAddress : String,
                postalCode : String
            }
            coords : {
                type : [Number],
                index : '2dsphere'
            }
        }
    ]
})

该集合上只有一个2dsphere索引,正如我所提到的,它可以通过shell工作,但无法与mongoose一起使用。

编辑:我尝试了其他一些方法,但都没有成功:

回退到使用mongodb原生驱动程序(同样出现错误,因此我认为是mongodb而不是mongoose导致问题):

Store.collection.geoNear(
    { type : "Point", coordinates : [-3.978, 50.777]}, 
    { spherical : true, limit : 10 }, 
    function (error, results, stats) {
    //do stuff with results here
});

使用遗留坐标而不是地理点(mongoose和本地均相同的错误):

Store.geoNear(
    -3.978, 50.777, 
    { spherical : true, limit : 10 }, 
    function (error, results, stats) {
    //do stuff with results here
});

使用mongoose的runCommand(这会有不同的错误,说Store.db.command不是一个函数 - 从mongoose中调用这个命令的正确方式将是可接受的答案):

Store.db.command({
    geoNear : "stores",
    near : { type : "Point", coordinates : [ -3.978, 50.777 ] },
    spherical : true,
    limit : 10
}, function(error, results){})
1个回答

1

最终成功找到了如何通过 MongoDB 原生驱动程序回退使用 runCommand 的方法:

Store.db.db.command({
    geoNear : "stores",
    near : { type : "Point", coordinates : [ -3.978, 50.777 ] },
    spherical : true,
    limit : 10
}, function(error, results){})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接