【发布时间】:2014-07-30 03:42:24
【问题描述】:
现在,这个 expressJS 调用将逗号分隔的值提供给一个导致 .find 的 mongoose .count,但分别返回计数和值..
我将如何将结果构造为一个数组,其中包含每个搜索的标签 + 有多少故事有该标签的计数,以一种看起来像这样的方式(使用模板引擎循环):
标签:[{标签:标签1,计数:4},{标签:标签2, 计数:2 }]
这是快递/猫鼬:
router.route('/tag/:tags')
// get the list of tags for userGenerated tags
// accessed by GET at http://localhost:4200/api/v1/tag/tag1,tag2
.get(function(req, res) {
var tags = req.params.tags.split(',');
console.log(tags); // ['tag1', 'tag2']
Story.count( { tags: { $in: tags } }, function (err, count) {
if (err)
res.send(err);
console.log('there is/are %d story(ies) with this/these tag(s)', count);
if (count >= 1) {
Story.find( { tags: { $in: tags } }, 'tags', function(err, stories) {
if (err)
res.send(err);
res.json(storytags);
}); // find and return tags of stories
} // if count >= 1
if (count < 1) {
res.json({ message: count + ' results' });
} // if count < 1
}); // .count
}); // get list of tags
【问题讨论】:
-
你所说的“各自计数”是什么意思?您能否解释更多您的预期输出中的内容
tags : [ { element: element1, count: count1 }, { element: element2, count: count2 } ](故事是元素吗?计数是标签出现在故事中的次数吗?) -
@dylants 一个更符合上下文的 json 输出将是
tags : [ { tag: tag1, count: 4 }, { tag: tag2, count: 2 } ](故事是具有标签数组的数据库文档),其中将返回一个包含每个查询标签的数组,并且标签的计数(出现该标签的故事) -
那么对我来说第一个
Story.count不是必需的,因为它会计算包含这些标签的所有故事。您需要的是第二个查询,即上面的Story.find,然后可能会遍历那些故事,收集您需要在您描述的tags块中输出的统计信息。
标签: javascript node.js mongodb mongoose aggregation-framework