在 mongoose 上自定义 json 输出

Customizing json output on mongoose

我是猫鼬和 mongoDB 的新手,我已经能够通过模型从查询中获得 json 响应。但是,我想知道如何使用猫鼬从多个查询中获得自定义 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"
            },
            ...
        ]
    }

您可以将 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 pipeline stage tries to group the data to process them. The $group 管道运算符类似于 SQL 的 GROUP BY 子句.在您的情况下,您为分组提供 _id 值,空值表示您正在对集合中的所有文档进行分组。

与 SQL 类似,除非使用任何聚合函数,否则不能使用 GROUP BY。同样,您也必须在 MongoDB 中使用聚合函数。在这种情况下,您需要 $push operator to create the data array. The other field totalCount is then accumulated using the $sum 运算符。

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

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

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

res.json(newResp);