【问题标题】:How to execute runCommand with Mongoose?如何使用 Mongoose 执行 runCommand?
【发布时间】:2011-08-17 04:43:11
【问题描述】:

我正在使用 Node.js 和 Mongoose 来访问我的 MongoDB。我正在使用一个存储一些地理坐标的模型。我将它们编入索引,一切似乎都按预期工作。我想做的是从我的请求中检索最接近的东西。在 MongoDB 控制台上,我执行以下操作:

distances = db.runCommand({ geoNear : "deals", near : [11.252, 14.141], spherical : true, maxDistance : 300  }).results 

但是,我不确定如何使用 Mongoose 执行此操作。以下是有关我尝试使用的命令的更多信息:http://www.mongodb.org/display/DOCS/Geospatial+Indexing

谢谢, 何塞

【问题讨论】:

    标签: mongodb node.js mongoose


    【解决方案1】:

    我认为 Mongoose 目前不支持 runCommand。您最好使用 find 方法使用地理空间选项,例如>

    db.places.find( { location : { $near : [50,50] , $maxDistance : 300 } } )
    

    【讨论】:

    • 但这并没有返回我想要的距离!有什么想法吗?
    【解决方案2】:
    YourModel.db.db.executeDbCommand({geoNear : "locations", near : [11.252,14.141], spherical: true }, function(err,res) { console.log(res.documents[0].results)});
    

    节点 0.6.6, 猫鼬@2.4.9, mongodb版本v2.0.2

    它有点老套,可能会改变。

    【讨论】:

    • 这不再适用于 3.6x。浏览 API 文档,我没有看到任何可比的东西。你知道另一种方法来实现这一点吗?
    • YourModel.db.db.command({geoNear : "locations", near : [11.252,14.141],spherical: true }, function(err,res) { console.log(res.documents [0].results)});
    【解决方案3】:

    首先,目前还没有一个方便的包装器可以直接将 geoNear 与 Mongoose 一起使用(假设您想读取计算出的距离)。

    但是由于 Mongoose 集合 proxies all collection methods 来自本机 MongoDB native driver,您可以只使用他们的 geoNear method,尽管您必须放弃一些您可能期望从 Mongoose 获得的便利,并且在我的发现中,错误处理是一个有点不同。

    无论如何,这就是您可以使用上述 API 的方式:

    YourModel.collection.geoNear(lon, lat, {spherical: true, maxDistance: d}, function(err, docs) {
      if (docs.results.length == 1) {
        var distance = docs.results[0].dis;
        var match = docs.results[0].obj;
      }
    });
    

    请参阅文档以了解正确的错误处理和how to calculate the distances

    【讨论】:

      【解决方案4】:

      希望这应该有效!参考网址: http://mongoosejs.com/docs/api.html

      // 遗留点

      Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) {
         console.log(results);
      });
      

      //geoJson

      var point = { type : "Point", coordinates : [9,9] };
      Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err, results, stats) {
         console.log(results);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-07
        • 2014-02-12
        • 2015-04-07
        • 1970-01-01
        • 2013-04-10
        • 2012-10-24
        • 2018-04-03
        相关资源
        最近更新 更多