2017-03-07 39 views
4

我寫了下面的模式在我的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: [] 

數組「supports」爲空。

+0

順序應該是'[lon,lat]'在您的centerSphere座標中。更多在這裏https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere – Veeram

+0

我修好了,但仍然沒有工作... – pittuzzo

+0

不完全確定。你是否也修復了文件? – Veeram

回答

2

該代碼是完美的!只是座標值不會被保存爲數字。 所以模式應該成爲:在DB

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

和座標數據將現在

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

而值爲之間的「」前:

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

我會建議將你的then轉換爲'Number'類型,而不是讓模式處理它。明確的輸入可以幫助以後識別錯誤,就像如果你想在後面對數值進行算術運算一樣。假設你想把經度增加5度,那麼''32.4532「+ 5'就是這樣評價的,因此''32.45325」'把數字連接到字符串的末尾,而不是將2加起來。明確地確保你的類型可以是好的防止這些的方法。 – tsturzl

+0

將字符串轉換爲數字類型'var num = + str'的​​簡短方法是在字符串前面使用'+'運算符,如果字符串不是數字,則返回'Nan'。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_(.2B)更多信息請參閱「Unary Plus」。 – tsturzl