MongoDB $ geoWithin $ centerSphere查询

时间:2017-03-07 21:55:15

标签: node.js mongodb

我在Node.js服务器中编写了以下架构:

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);

然后我写了我的调度员,用于添加,删除和研究。 添加和删​​除都可以,但我在研究方面存在一些问题。

这是我的路线:

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
                });
            }
        });
    })

我的SupportManager.getGuides是以下代码:

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

奇怪的是我在db中添加了以下对象:

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

但是当我进行研究时,使用lat = 22和long = 34,我会收到

的答案
success: true,
message: 856,
supports: []

阵列"支持"是空的。

1 个答案:

答案 0 :(得分:2)

代码很完美!只是坐标值不会保存为数字。 因此Schema应该成为:

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

DB中的坐标数据现在是

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

而值之前是" " :

"loc": {
        "coordinates": [
            "34",
            "22"
        ],
        "type": "Point"
    },
相关问题