2014-09-05 91 views
1

從外部網絡API來的JSON看起來像這樣:處理JSON創建一個普通陣列代替JSON對象

[{matches: 
    [{ 
     "match_something":"123", 
     "match_something_else":"Potato", 
     "match_events": 
     [{ 
      "event_id":"42", 
      "event_desc":"redcard", 
     }, 
     { 
      "event_id":"1", 
      .. 
     }] 
    }, 
    // more matches 

所以,匹配陣列在其內的事件陣列爲每個匹配。

相關的處理代碼如下所示:

 _.each(matches, function(match) { 
      var results = new Results({ 
       _id: match.match_id, 
       match_date: match.match_formatted_date, 
       ft_score: match.match_ft_score, 
       match_events:[] 
      }); 
      events = match.match_events; 
      _.each(events, function(event) { 
       results.match_events.push({ 
        _id:event.event_id, 
        match_id:event.event_match_id, 
        type:event.event_type, 
        team:event.event_team, 
        player:event.event_player, 
       }); 
      }); 
      results_array.push(results); 
     }); 
     return results_array 

這是(簡稱爲簡潔起見)爲模型的架構:

var resultsSchema = new db.mongoose.Schema({ 
     _id:Number, 
     match_date:String, 
     status:String, 
     ... 
     match_events:[{ 
      _id: Number, 
      match_id: Number, 
      type:String, 
      ... 
     }] 
    }); 

然後,我從我的數據庫中看到(蒙戈)一旦完成,就是下面的JSON(爲了清楚起見刪除了額外的屬性):

[ 
{"_id":1931559, "ft_score":"[0-0]","__v":0, 
    "match_events": 
     ["19315591","19315592","19315593","19315594"]}, 

這讓我感到困惑。這些ID是正確的,我檢查了服務器數據。處理代碼只是創建這些ID的數組,而不是每個事件的JSON對象。

難道不應該顯示爲:

..."match_events": 
    [{"_id:" "19315591", ...}] 
+0

我不熟悉這個數據庫,但不是_id保留?我的意思是你確定你可以用嵌套結構中的_id定義一個對象嗎?它似乎將它解釋爲一個內部鏈接,或類似的東西。我會嘗試沒有_id ...代碼似乎是好的,所以這是一個奇怪的錯誤... – inf3rno 2014-09-05 02:14:52

+0

是的問題是與架構聲明一樣在下面的其他答案中指出。儘管如此,我確實刪除了_id,以免將來會引發問題。謝謝 – 2014-09-05 02:21:25

+0

@ inf3rno Mongoose將使用您在架構中爲'_id'明確聲明的任何「類型」,或者隱式添加一個未定義它的「ObjectId」。它甚至會嘗試將「以字符串形式提供的參數」轉換爲正確的類型。 – 2014-09-05 02:52:37

回答

3

你的架構定義是這裏的問題。 Mongoose使用「type」關鍵字來確定數據類型,所以它認爲「match_events」是一個「String」數組。

聲明是這樣,而不是:

var resultSchema = new Schema({ 
    _id: Number, 
    status: String, 
    match_events: [{ 
    _id: { type: Number }, 
    type: { type: String } 
    }] 
}); 

或者更好的是這樣的:

var eventSchema = new Schema({ 
    _id: Number, 
    type: String 
}); 

var resultSchema = new Schema({ 
    _id: Number, 
    status: String, 
    match_events: [eventSchema] 
}); 
+0

工作就像一個魅力馬上。感謝您爲第二次實施做出的額外努力。再次感謝尼爾的幫助,感謝它。 – 2014-09-05 02:20:30

+0

不錯,至少保留字部分是真的:-) – inf3rno 2014-09-05 02:20:43

+1

實際上啊!當我從模式中刪除_id時,只需看看mongo爲每個內部結構分配一個_id即可。所以它看起來是必需的:) – 2014-09-05 02:24:20