处理JSON创建一个普通数组而不是JSON对象

时间:2014-09-05 01:17:49

标签: javascript json node.js mongodb mongoose

来自外部Web API的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,
            ...
        }]
    });

然后,一旦完成,我从数据库(mongo)看到的是以下JSON(为清晰起见,删除了额外的属性):

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

这让我感到困惑。 ID是正确的,我检查了服务器数据。处理代码只是创建这些ID的数组,而不是每个事件的JSON对象。

不应该显示为:

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

1 个答案:

答案 0 :(得分:3)

您的架构定义是此处的问题。 Mongoose使用"类型"用于确定数据类型的关键字,因此它认为" 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]
});