【发布时间】:2020-04-12 20:35:07
【问题描述】:
我是节点 js 的新手。我有一个控制器函数,我在其中创建自己的对象和数组。但我无法在最终循环之外获得最终数组。我还注意到console.log("3") 不起作用并直接调用console.log("4");。
这里是代码
async function fetchLeague(req, res, next) {
try {
//get types
let types = await Leaguetype.find({});
let mainarray = {};
mainarray['filters'] = [];
console.log("1");
types.map(async (type) => {
console.log("2");
let typess = {};
typess.title = type.title;
typess.totalCards = '5';
typess.sections = [];
mainarray['filters'].push(typess);
var categories = await Leaguecategories.find({"league_type_id": type._id}) ;
categories.map(async (category) => {
console.log("3");
let allcategories = {};
allcategories.id = category._id;
allcategories.title = category.name;
allcategories.cards = [];
typess.sections.push(allcategories);
let card = await League.find({"league_category_id": category._id}) ;
card.map(async (league) => {
let allleague = {};
allleague.card_title = league.title;
allleague.pool_price = league.pool_price;
allleague.entry_fee = league.entry_fee;
allleague.total_spots = league.total_spots;
allleague.start_time = league.start_time;
allleague.end_time = league.end_time;
allcategories.cards.push(allleague);
});
});
});
console.log("4");
res.send({status: 0, statusCode:"success", message: "Successfully 1 inserted.", data: mainarray});
} catch (error) {
console.log('no', error);
return []
}
}
【问题讨论】:
-
你能检查
categories的值吗?console.log(categories).. 可能是返回一个空数组。 -
@MEDZ 当我
console.log(categories)它给了我一个包含我所有值的数组。 -
数字“4”是在它之前还是之后记录的?
-
与问题无关,但您正在循环访问 db,这不是一个好主意。我建议您一次性获取所有相关数据。
-
@SuleymanSah 你有任何例子吗?我对 nodejs 完全陌生
标签: javascript node.js mongoose promise