gpt4 book ai didi

javascript - 在循环中使用 promise 的 node js,mongodb 中没有得到结果

转载 作者:行者123 更新时间:2023-11-29 15:06:56 25 4
gpt4 key购买 nike

我是 nodejs 和 mongodb 的新手。对于新开发人员来说,在 nodejs 循环中使用 promise 确实非常令人困惑。我需要最终的数组或对象。然后()给我最终结果。请更正。
我有一个如下所述的 Controller 功能。

let League = require('../../model/league.model');
let Leaguetype = require('../../model/leagueType.model');
let Leaguecategories = require('../../model/leagueCategories.model');


let fetchLeague = async function (req, res, next){
let body = req.body;
await mongo.findFromCollection(Leaguetype)
.then(function(types) {
return Promise.all(types.map(function(type){
return mongo.findFromCollection(Leaguecategories, {"league_type_id": type._id})
.then(function(categories) {
return Promise.all(categories.map(function(category){
return mongo.findFromCollection(League, {"league_category_id": category._id})
.then(function(leagues) {
return Promise.all(leagues.map(function(league){
return league;
}))
.then(function(league){
console.log(league);
})
})
}))
});
}))

})
.then(function(final){
console.log(final);
})
.catch (error => {
console.log('no',error);
})
}

mongo.findFromCollection 函数看起来像这样。

findFromCollection = (model_name, query_obj = {}) => {
return new Promise((resolve, reject) => {
if (model_name !== undefined && model_name !== '') {
model_name.find(query_obj, function (e, result) {

if (!e) {
resolve(result)
} else {
reject(e);
}
})
} else {
reject({ status: 104, message: `Invalid search.` });
}
})
}

这是我的模型文件

var mongoose = require('mongoose');
const league_categories = new mongoose.Schema({
name: {
type: String,
required: true
},
active: {
type: String,
required: true
},
create_date: {
type: Date,
required: true,
default: Date.now
},
league_type_id: {
type: String,
required: 'league_type',
required:true
}
})

module.exports = mongoose.model('Leaguecategories', league_categories)

最佳答案

首先,我建议您尽可能停止使用回调,它有点过时并且代码更难阅读和维护。

我稍微重写了你的代码,以更接近我习惯的代码,这并不意味着这种风格更好,我个人认为它更容易理解发生了什么。

async function fetchLeague(req, res, next) {
try {
//get types
let types = await Leaguetype.find({});

//iterate over all types.
let results = await Promise.all(types.map(async (type) => {
let categories = await Leaguecategories.find({"league_type_id": type._id});
return Promise.all(categories.map(async (category) => {
return League.find({"league_category_id": category._id})
}))
}));

// results is in the form of [ [ [ list of leagues] * per category ] * per type ]
// if a certain category or type did not have matches it will be an empty array.
return results;
} catch (error) {
console.log('no', error);
return []
}
}

关于javascript - 在循环中使用 promise 的 node js,mongodb 中没有得到结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59029632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com