MongoDB $ geoWithin $ centerSphere查询
我在我的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); },
奇怪的行为是我在我的数据库中添加了以下对象:
{ "_id": "58bf2f07d5fd2a0cdde4cca9", "guide": "a1", "loc": { "coordinates": [ "34", "22" ], "type": "Point" }, "title": "tappp", "__v": 0 }
但是当我做研究时,使用lat = 22和long = 34,我收到答案
success: true, message: 856, supports: []
数组“支持”是空的。
代码是完美的! 只是坐标值不会保存为数字。 所以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" },