【问题标题】:How to iterate a JSON array and add data from an async arrow function?如何迭代 JSON 数组并从异步箭头函数添加数据?
【发布时间】:2020-11-29 12:03:26
【问题描述】:

我是 MEAN 堆栈和 JS 的新手。我想要完成的是调整我从数据库中获得的响应,添加另一个字段。 我有一个 mongoose 方法,它为我提供了所有存在的 课程,我想将每个课程的所有 Inscriptions 添加到该信息中。所以我正在尝试这个:

exports.getAllCourses = async(req, res) => {
    try {
        const rawCourses = await Course.find();
        const courses = await courseAdapter.apply(rawCourses)
        await res.json({courses});
    } catch (error) {
        console.log(error);
        res.status(500).send("Ocurrio un error imprevisto :/");
    } 
};

我的课程适配器

exports.apply = (courses) => {
    return courses.map(async course=> (
        {
            ...course._doc,
            number: await coursetUtils.getNumberOfInscriptions(course._doc._id)
        }
    ));
}

还有我的 courseUtils:

exports.getNumberOfInscriptions = async courseId => {
       return await CourseInscription.countDocuments({courseId: courseId});
}

我认为我的问题在于 async-await 函数,因为使用此代码我得到了:

{"courses":[
  {},
  {}
]}

或者改变一些东西我明白了:

{"courses":[
  {"courseInfo":{...},
   "number":{}
  },
  {"courseInfo":{...},
   "number":{}
  }
]}

但从来没有响应上的题字数。顺便说一句,我在代码的其他部分中使用函数 getNumberOfInscriptions() 进行验证和工作。

【问题讨论】:

  • 你需要在上面加上Promise.all

标签: javascript json mongoose mean


【解决方案1】:

尝试了很多东西我得到了这个: 我在 apply 函数中更改了处理 DB 数据的方式,并将其视为数组。

exports.apply = async (courses) => {
    var response = [];
    for (let c of courses) {
        var doc = c._doc;
        var tmp = [{course: doc, inscriptionNumber: await courseUtils.getNumberOfInscriptions(c._doc._id)}];
        response = response.concat(tmp);
    }
    return response;
}

我认为这不是实现目标的好方法,但它确实有效。如果我发现更好、性能或清洁的东西,我会发布。

无论如何,当我调用 async-await 函数时,我仍然不知道我之前的 map 函数做错了什么。如果有人知道,请告诉我。

【讨论】:

    猜你喜欢
    • 2014-08-28
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2017-08-15
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    相关资源
    最近更新 更多