我尝试计算每篇文章的数量,但结果不是我想要的
这是我的代码
var nameWebsites = await Article.distinct("website.name");
var idWebsites = await Article.distinct("website.id");
var numberArticle = [];
var result = [];
for(var i = 0; i < nameWebsites.length; i++) {
await Article.aggregate([
{ $match: {"website.id": idWebsites[i]}},
{ $count: "count"}
], function(err, result){
numberArticle.push(result);
});
}
for(var i = 0; i < nameWebsites.length; i++) {
result.push({"id":idWebsites[i], "name":nameWebsites[i], "number_article": numberArticle[i]});
}
这是结果的一部分
{"data":[{"id":1,"name":"Dan tri","number_article":[{"count":52952}]},...]}
我想要这样的结果:
{"data":[{"id":1,"name":"Dân trí","number_article":52952},...]}
答案 0 :(得分:0)
var objectArray = {"data":[{"id":1,"name":"Dân trí","number_article":52952}]}
然后您可以使用
objectArray.data.length
答案 1 :(得分:0)
获取数组中第一个对象的numberArticle[i]
,而不是获取count
的全部结果。
for(var i = 0; i < nameWebsites.length; i++) {
result.push({
id: idWebsites[i],
name: nameWebsites[i],
number_article: numberArticle[i][0].count,
});
}