MongoDB $ geoWithin $ centerSphere request

I wrote the following diagram on 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 to add, remove, and research. Adding and removing is fine, but I have some research issues.

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.getGuidesis the following code:

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

The strange behavior is that I added the following object to my db:

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

But when I do research using lat = 22 and long = 34, I get an answer with

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

The array "supports" is empty.

+4
source share
1 answer

The code is perfect! Just the coordinate value is not stored as Number. So, the scheme should become:

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

And the coordinate data in the database will now be

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

"":

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

Source: https://habr.com/ru/post/1671748/


All Articles