Search code examples
javascriptnode.jsmongodbasync-awaitmongoose-schema

async await not working properly in mongo query


I have a project collection. Under the project schema have a property called tasks which is an array with the ids of the tasks. Now I am trying to write an api for singleProject, which should include the project details with a property taskDetails which will contain the detail of the tasks under the project. And for getting the task details I am using the ids which I stored in the task property under project. Below is the code I am using :

exports.getSingleProject = async (req, res) => {
  req.project.logo = undefined;

  await req.project.tasks.map((taskItem, index) => {
    taskSchema.find({ _id: taskItem.toString() }).exec((err, task) => {
      req.project.tasksDetails.push(task);
    });
  });

  responseMessages(
    res,
    200,
    true,
    "Single project fetched successfully.",
    req.project
  );
};

but in the response getting taskDetails as an blank array. I guess I am using async await in wrong place. Need some help on this. Thanks in advance


Solution

  • The await keyword only works with a promise: an array is not a promise, but you can map to a promise and wait for all promises to resolve using Promise.all - see example below:

    const tasks = await Promise.all(req.project.tasks.map(item => new Promise((accept, reject) => { 
        taskSchema.find({ _id: taskItem.toString() }).exec((err, task) => {
        
            if(err) {
                reject(err);
                return;
            }
    
            accept(task);
        });
    });
    

    The tasks variable would be an array of your tasks, which you can return in the response.