【问题标题】:Customizing json output on mongoose在猫鼬上自定义 json 输出
【发布时间】:2016-04-20 01:29:11
【问题描述】:

我是 mongoose 和 mongoDB 的新手,我已经能够通过模型从查询中获得 json 响应。但是,我想知道如何使用 mongoose 从多个查询中获得自定义 json 输出。我目前写的代码如下。

var ArticleSchema = new Schema({
  title: {
    type: String,
    default: ''
  },
  content: {
    type: String,
    default: ''
  }
});

mongoose.model('Article', ArticleSchema);


exports.list = function (req, res) {
  Article.find().exec(function (err, articles) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(articles);
    }
  });
};

输出是
{
    [
        {
            "title": "Super Hero 1",
            "content": "Superman"
        },
        {
            "title": "Super Hero 2",
            "content": "Batman"
        },
        ...
    ]
}

现在假设我想生成如下的json,怎么做?

{
     "totalCount": 50, //total count of the query
     "data":  [
            {
                "title": "Super Hero 1",
                "content": "Superman"
            },
            {
                "title": "Super Hero 2",
                "content": "Batman"
            },
            ...
        ]
    }

【问题讨论】:

    标签: json mongodb express mongoose mean-stack


    【解决方案1】:

    如果您只需要构建响应,这将是最简单的方法。

    var newResp = [{ "totalCount": listings.length , "data": listings }];
    
    res.json(newResp);
    

    【讨论】:

      【解决方案2】:

      您可以将 aggregation framework 与以下管道一起使用:

      exports.list = function (req, res) {
          var pipeline = [
              {
                  "$group": {
                      "_id": null,
                      "data": {
                          "$push": {
                              "title": "$title",
                              "content": "$content"
                          }
                      },
                      "totalCount": { "$sum": 1 }
                  }
              },
              {
                  "$project": {
                      "_id": 0, "totalCount": 1, "data": 1
                  }
              }
          ];
      
          Article.aggregate(pipeline).exec(function (err, articles) {
              if (err) {
                  return res.status(400).send({
                      message: errorHandler.getErrorMessage(err)
                  });
              } else {
                  res.json(articles);
              }
          });
      };
      

      管道的结构方式是,您的第一步,$group 管道阶段会尝试对数据进行分组以处理它们。 $group 管道运算符类似于 SQL 的 GROUP BY 子句。在您的情况下,您通过键为组提供 _id 值,空值表示您正在对集合中的所有文档进行分组。

      与 SQL 类似,除非您使用任何聚合函数,否则您不能使用 GROUP BY。同样,您也必须在 MongoDB 中使用聚合函数。在这种情况下,您需要 $push 运算符来创建 data 数组。然后使用 $sum 运算符累加另一个字段 totalCount

      使用 $project 运算符的最后一步涉及更改最终文档的属性,以便删除 _id 字段。

      【讨论】:

      • 很好的解释。将深入探讨聚合框架。非常感谢。
      • @stackdisplay 不用担心,乐于助人:)
      猜你喜欢
      • 2018-01-21
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 2018-08-03
      • 2017-05-27
      • 2019-03-02
      相关资源
      最近更新 更多