【问题标题】:Sails.js $near query does not work and asks for indicesSails.js $near 查询不起作用并要求索引
【发布时间】:2015-01-06 19:06:52
【问题描述】:

我正在尝试使用 MongoDB 查询 Sails.js 中某个坐标的最近点,但出现以下错误:

{ [MongoError: can't find any special indices: 2d (needs index), 2dsphere (needs index),  for: { $near: { $geometry: { type: "Point", coordinates: [ "4.3795912", "51.9985675" ] }, $maxDistance: 1000 } }] name: 'MongoError' }

我确定我在 bootstrap.js 中有这个:

sails.models.location.native(function (err, collection) {
        collection.ensureIndex({ coordinates: '2dsphere' }, function () {


            cb();

        });
    });

我的Location 模型看起来像这样:

attributes: {

      coordinates: {
          type: 'json'
      },
      user: {
          model: 'user'
      }
  }

我的控制器代码如下:

Location.native(function(err, collection) {

            var query = {};

            collection.find(
                query.coordinates = {
                    $near: {
                      $geometry: {
                        type: "Point",  
                        coordinates: [
                          user.locations[0].lng, 
                          user.locations[0].lat 
                        ]
                      },
                      $maxDistance : 1000 
                    }
                  }
                ).toArray(function(err, result){
                        if(err) {
                            console.log(err);   
                        }
                        else 

                            return res.json(result);
                });
        });

我很确定我做了我应该做的事,但显然我做错了什么或忘记了什么。有人知道如何让它工作吗?谢谢。

【问题讨论】:

  • 前段时间我遇到了一些困难。确保您正在阅读您正在运行的 MongoDB 版本的正确文档。 API 在最近的版本中发生了相当大的变化。

标签: mongodb sails.js mongodb-query sails-mongo


【解决方案1】:

我已经解决了这个问题。我做错了两件事。首先,每次我调用sails lift 时,我创建的索引都会被删除,而我并不知道。第二个问题是我的定位点不是正确的GeoJSON 格式:

{
          "type": "Point",
          "coordinates": [
            4.373654,
            51.998715
          ]
        }

【讨论】:

  • 为什么使用 'sails lift' 会删除索引,仅在您的情况下或一般来说......第一次听到!
  • @securecurve 我不知道它是否仍然相同,但是控制台会在“起航”之后要求输入一个数字(1、2 或 3),而 3 意味着数据库中的所有内容都会被删除,当然还有索引。
  • 哦,我明白了..这很自然:)
猜你喜欢
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 2020-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多