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.