從外部網絡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", ...}]
我不熟悉這個數據庫,但不是_id保留?我的意思是你確定你可以用嵌套結構中的_id定義一個對象嗎?它似乎將它解釋爲一個內部鏈接,或類似的東西。我會嘗試沒有_id ...代碼似乎是好的,所以這是一個奇怪的錯誤... – inf3rno 2014-09-05 02:14:52
是的問題是與架構聲明一樣在下面的其他答案中指出。儘管如此,我確實刪除了_id,以免將來會引發問題。謝謝 – 2014-09-05 02:21:25
@ inf3rno Mongoose將使用您在架構中爲'_id'明確聲明的任何「類型」,或者隱式添加一個未定義它的「ObjectId」。它甚至會嘗試將「以字符串形式提供的參數」轉換爲正確的類型。 – 2014-09-05 02:52:37