【发布时间】: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