Sails.js $ next to query doesn't work and asks for indices

I am trying to query the closest points to some coordinate in Sails.js using MongoDB, but I am 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 model Location

looks like this:

attributes: {

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

      

My controller code is as follows:

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 exactly what I was supposed to do, but apparently I did something wrong or forgot something. Does anyone know how to get this to work? Thank.

+3


source to share


1 answer


I solved the problem. There were two things I did wrong. First of all, every time I called sails lift

, the index I created got deleted and I didn't know it. The second problem was that my location point was not in GeoJSON format :



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

      

0


source







All Articles