简体   繁体   中英

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

I'm new on MEAN stack and also on 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. 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:

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:

{"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.

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.

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. If anybody knows, please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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