Friday, March 17, 2017

MongoDB $geoWithin $centerSphere query

Leave a Comment

I wrote the following schema in my Node.js server:

var mongoose = require('mongoose'); var Schema = mongoose.Schema; var config = require('../../config.js');  var schema = new Schema({         title   : { type: String, default: "generic"},         guide   : String,         loc     : {             type : {type: String, default:"Point"},             coordinates : [ ]         },     } ); schema.index({"loc":"2dsphere"}); module.exports = mongoose.model(config.DATA_TYPE.SUPPORT, schema); 

Then I wrote my dispatcher for adding, removing and research. Adding and removing are ok but I have some problem with research.

This is my route:

router.route('/')     .post(function(req, res, next){         SupportManager.getGuides(req.body.lat, req.body.lon, function(err,data){             if(err){                 return res.json({                         success: false,                         message: 756                 });             }else{                 return res.json({                         success: true,                         message: 856,                         supports: data                 });             }         });     }) 

where my SupportManager.getGuides is the following code:

getGuides: function(lat,lon,callback){         Support.find({ loc: { $geoWithin: { $centerSphere: [[ lon , lat], 10/3963.2]}}}, callback);     }, 

The strange behaviour is that I added the following object in my db:

{     "_id": "58bf2f07d5fd2a0cdde4cca9",     "guide": "a1",     "loc": {         "coordinates": [             "34",             "22"         ],         "type": "Point"     },     "title": "tappp",     "__v": 0 } 

But when I do the research, using lat=22 and long=34, I receive the answer with

success: true, message: 856, supports: [] 

The array "supports" is empty.

1 Answers

Answers 1

The code is perfect! Just the coordinates value are not saved as Number. So the Schema should become:

var schema = new Schema({         title   : { type: String, default: "generic"},         guide   : String,         loc     : {             type : {type: String, default:"Point"},             coordinates : [ { Number } ]         },     } ); 

And the coordinates data in DB will be now

"loc": {         "coordinates": [             34,             22         ],         "type": "Point"     }, 

while before the values were between the " " :

"loc": {         "coordinates": [             "34",             "22"         ],         "type": "Point"     }, 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment