4

I'm trying to query the nearest points to some coordinate in Sails.js using MongoDB, but I'm getting the following error:

{ [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' }

I made sure I had this in bootstrap.js:

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


            cb();

        });
    });

And my Location model looks like this:

attributes: {

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

My controller code is the following:

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);
                });
        });

I'm pretty sure I did just what I was supposed to do, but apparently I have done something wrong or I forgot something. Anyone any idea how to get this to work? Thanks.

Loolooii
  • 8,588
  • 14
  • 66
  • 90
  • 2
    I had some difficulties with this a while back. Make sure you're reading the right docs for the version of MongoDB you're running. The API has changed a fair bit across recent versions. – Chris Houghton Jan 06 '15 at 19:20

1 Answers1

1

I have solved the problem. There were two things I did wrong. First of all, every time I called sails lift the index I created would get removed and I did not know that. Second problem was that my location point was not in proper GeoJSON format:

{
          "type": "Point",
          "coordinates": [
            4.373654,
            51.998715
          ]
        }
Loolooii
  • 8,588
  • 14
  • 66
  • 90
  • Why does using 'sails lift' will remove indexes, is that only in your case or generally speaking .. first time to hear that! – securecurve Sep 10 '15 at 13:09
  • @securecurve I don't know if it's still the same, but the console would ask for a number (1, 2 or 3) after "sails lift" and 3 meant that everything in the db would get removed and naturally also the indexes. – Loolooii Sep 11 '15 at 08:26
  • Oh, I see .. which is natural :) – securecurve Sep 11 '15 at 08:57