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

标签 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", ...}]

最佳答案

您的模式定义是这里的问题。 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]
});

关于javascript - 处理 JSON 创建一个普通数组而不是 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25677327/

相关文章:

javascript - 使用javascript使用动画更改文本onclick div

javascript - 浏览器特定/条件 JS

javascript - 根据值加载页面时显示 div

java - 无法从json文件打印json数组的所有键和值

javascript - 如何在 div 中添加标签

javascript - 对象操作以形成新对象

ajax - 在 URL Hash/Fragment 中存储 JSON 的最佳实践

node.js - node.js 中的代理身份验证与模块请求

node.js - 如何在 PM2 中运行 2 个独立的应用程序?

node.js - Dialogflow - Google 助理 : setFollowupEvent after showing a message