$near not working in sails.js

815 views
Skip to first unread message

Jignesh Jigs

unread,
Mar 21, 2014, 11:33:51 AM3/21/14
to sai...@googlegroups.com, Vadorequest Mini Vado
Hello ,

i am working on sails.js but $near operator not working ..

Can u please help me..

In model i declare like this ->latlong:{    type:'array'  }

 var coords = [25,50];
        Restaurant.find({ latlong : { $near: coords }}).limit(1).exec(function(err, res) {
          console.log("Closest to %s is %s", coords, res);
         
        });

Await for yr reply..

Regards,
JIgnesh

John Tomaselli

unread,
Mar 28, 2014, 9:58:46 PM3/28/14
to sai...@googlegroups.com, Vadorequest Mini Vado
You have to use Mongodb native as waterline does not support this. I actually had an engineer at Mongodb help me with the parameters.
The data must be in the following and is case sensitve
"ziplocation" : {
        "type" : "Point",
        "coordinates" : [ 
            -73.968, 
            40.758
        ]
    }
Good luck and let me know.
John

I use geoNear in the working example
  var vlimit = 500;// max no of records to return
var pagesize = 30;
var searchObj = {};
 lng = ziplist.LONGITUDE;
 lat = ziplist.LATITUDE;

var startpos = req.param('startpos');
......
lng
Providers.native(function (err, collection) {
                    collection.geoNear(lng, lat, {
                        num:vlimit, // max no of records to return limit: does not work
                        distanceMultiplier:3959,
                        maxDistance: vmaxDistance/3959,
                        query: searchObj, // filter
                        spherical: true
                    }, function (mongoErr, docs) {

                        if (mongoErr) {
                            console.error(mongoErr);
                            return res.send('geoProximity failed with error=' + mongoErr);
                        } else {
                            var returnCt =docs.results.length;
                            var providers= [];
                           
                            _.forEach(docs.results, function (result) {
                                providers.push(_.extend(result.obj, {
                                    dis: result.dis
                                }))
                            });
                           
                            var returnArray = dentists.splice(startpos, pagesize);
                            // push the last record with stats
                            returnArray.push({ reccount: returnCt});
                            console.log('returnCt=', returnCt);
                            return res.json({ data: returnArray });
                        }
                    });

John Tomaselli

unread,
Mar 28, 2014, 10:12:43 PM3/28/14
to sai...@googlegroups.com, Vadorequest Mini Vado


On Friday, March 21, 2014 11:33:51 AM UTC-4, Jignesh Jigs wrote:

Vikram Mirla

unread,
Nov 1, 2014, 4:32:05 PM11/1/14
to sai...@googlegroups.com, ambroise...@gmail.com
Hi Sails team,

I am a sails.js beginner. 

I have an app developed with node.js and express, where I have a model definition for 
location as :


  loc: { type:[Number], index:'2d'}

Sails.js does nto recognize it.
So instead I used.

loc: {
       type: 'array'
    },


Now, I am not sure how to query for nearest values to a location.

With mongoose, I was able to use $near. Like this:

      Comment.find( {loc:  {$near: [ parseFloat(req.query.lon), parseFloat(req.query.lat) ],$maxDistance:20  }})

What would be equivalent with Waterline?/ Sails.js?

Would appreciate hints here. I wish to continue with Sails.js, but have been facing these migration issues.


Thanks

Vikram

Vikram Mirla

unread,
Nov 3, 2014, 11:01:24 PM11/3/14
to sai...@googlegroups.com, ambroise...@gmail.com
Hello All,

To the benefit of the community, I am copying a link which helped me get 'geoNear' working

https://github.com/balderdashy/sails-mongo/issues/46

I made few mistakes - which took more time:

- I have two 2dsphere indices in my model. 

geoNear requires that there should be only one attribute in model with 2dsphere index

-  I was incorrectly passing latitude first to geoNear function:
Right way is as follows:




User.native(function(err, collection) {

collection.geoNear(lng, lat, {
limit: 30,
maxDistance: 1000, // in meters
//query: {}, // allows filtering
distanceMultiplier: 3959, // converts radians to miles (use 6371 for km)
spherical : true
}, function(mongoErr, docs) {
if (mongoErr) {
console.error(mongoErr);

res.send('geoProximity failed with error='+mongoErr);
} else {
          console.log('docs=',docs);
// res.send('proximity successful, got '+docs.results.length+' results.');
res.json(docs.results);
}
});
});

Other thing I learnt which could benefit others. In config/bootstrap.js file, if you were to set multiple configurations , use async.



var async = require('async');

module.exports.bootstrap = function(cb) {

function updateUserStatus (done) {
User.update({}, {
online: false
},
function userUpdated(err, users) {
if (err) {
console.log(err);
return done(err);
} else {
return done();
}

}
)
}


function geoStuff (done) {

User.native(function (err, collection) {
collection.ensureIndex({ location: '2dsphere' }, function () {
return done();
});
});
}

async.parallel([ updateUserStatus, geoStuff], cb)


};

and my Model user.js has this config.

    location: {
       type: 'json', index:'2dsphere'
    },

Mongodb entry looks like this:

{
  _id: ObjectId("5458434c6fd369ca07e0917b"),
  admin: true,
  createdAt: ISODate("2014-11-04T03:09:00.980Z"),
  email: "mirl...@gmail.com",
  encryptedPassword: "$2a$10$Y4142XzCoVNhJKLqEx934eGCAauLz2RcTzJCHO64QDrvZruMjD8SS",
  location: {
    type: "Point",
    coordinates: [
      -73.968,
      40.758
    ]
  },
  name: "mirla",
  online: true,
  title: "mirla",

}


Thanks ,

Vikram
Reply all
Reply to author
Forward
0 new messages