Search code examples
javascriptnode.jsmongodbasynchronousmongoose

Fetching documents from Mongoose inside a map function returns Promise pending as well as the data


So I have this array of strings which I'm using as filter to fetch documents from MongoDB using Mongoose. I'm successfully getting the data back from the db, but it is also returning Promise { <pending> } on the console even though I'm wrapping the map function with Promise.all.

Please note that this map function is nested inside two level deep for in loops which I'm leaving out for simplicities sake.

Suppose this is the array of strings:

const subCategories = [ 'Politics', 'Entertainment' ];

And this is the map function:

const subCategoryID = await Promise.all( subCategories.map( async item => {
  try {
    const data = await SubCategory.findOne( { subCategory: item } );
    return data;
  } catch( e ) {
    throw err;
  }
}));

console.log( subCategoryID );

Promises make my head spin. I have tried learning Promises more than 5-6 times in the last 1-2 years and it still confuses me. So if you can, please provide a solution with Async/Await.


Solution

  • If you're only interested in the result, Try this approach:

    const subCategories = [ 'Politics', 'Entertainment' ];
    
    const queries = subCategories.map((i) => {
      return { subCategory: i };
    });
    
    const subCategoryID = await SubCategory.find({
      $or: queries,
    });
    
    console.log(subCategoryID);
    
    

    using $or operator is explained in mongodb manual:

    The $or operator performs a logical OR operation on an array of two or more <expressions> and selects the documents that satisfy at least one of the <expressions>.

    more about it here.

    In mongoose, you can use it in any find methods.

    for explanation about your promise, sorry I can't help.

    Please mark answered if this solves your problem.