代码之家  ›  专栏  ›  技术社区  ›  Carasel

geoNear异常:“near”字段必须是点

  •  5
  • Carasel  · 技术社区  · 10 年前

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

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

    我正在尝试将其转换为节点服务的猫鼬查询 as shown in the docs .

    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工作,只是不适用于猫鼬。

    编辑: 其他我尝试过但没有成功的事情:

    回到使用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
    });
    

    回到使用传统坐标而不是地理点(猫鼬和本地(相同错误)):

    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 回复  |  直到 10 年前
        1
  •  1
  •   Carasel    10 年前

    最终设法解决了如何恢复使用 runCommand 通过mongodb本机驱动程序:

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