无法在节点js中获得结果,mongo db在循环中使用promise

时间:2019-11-25 10:22:31

标签: javascript node.js mongodb promise

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

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)

1 个答案:

答案 0 :(得分:1)

首先,我建议您在任何可能的地方停止使用回调,因为它有些陈旧,并且代码更难以阅读和维护。

我重新编写了一些代码以使其看起来更接近我的习惯,这并不意味着这种风格更好,我个人认为它更容易理解正在发生的事情。

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 []
    }
}
相关问题