简体   繁体   English

如何迭代 JSON 数组并从异步箭头 function 添加数据?

[英]How to iterate a JSON array and add data from an async arrow function?

I'm new on MEAN stack and also on JS.我是 MEAN 堆栈和 JS 的新手。 What I'm trying to accomplish is to adapt the response that I get from the DB adding to it another field.我想要完成的是调整我从数据库中获得的响应,添加另一个字段。 I have a mongoose method that gave me all the Courses that exist and I want to add to that information all the Inscriptions for each one.我有一个 mongoose 方法,它为我提供了所有存在的课程,我想将每个课程的所有铭文添加到该信息中。 So I'm trying this:所以我正在尝试这个:

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 :/");
    } 
};

My courseAdapter我的课程适配器

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

And my courseUtils:还有我的课程Utils:

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

I think my problem is with the async-await function because with this code i get this:我认为我的问题在于async-await function 因为使用此代码我得到了这个:

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

or changing some stuff i get this:或改变一些东西我得到这个:

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

But never the number of inscription on the response.但从来没有数过题字上的反应。 By the way i use function getNumberOfInscriptions() in other part of my code for make a validation and works.顺便说一句,我在代码的其他部分使用 function getNumberOfInscriptions()进行验证和工作。

Trying a lot of stuff i get to this: I change the way I process the data from DB in the apply function and I treat it like an array.尝试了很多东西我得到了这个:我改变了我在应用function 中处理来自 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;
}

I think is not a pretty good way to accomplish my goal, but it works.我认为这不是实现我的目标的好方法,但它确实有效。 If I find something better, performance or clean I will posted.如果我发现更好的东西,性能或清洁,我会发布。

Anyways I still don't know what I was doing wrong on my previous map function when I call my async-await function.无论如何,当我调用我的async-await function 时,我仍然不知道我之前map function 做错了什么。 If anybody knows, please let me know.如果有人知道,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM