简体   繁体   中英

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.

If you want the result, Try this:

const singleCategoryQuery = subCategories.map((i) => {
  return { subCategory: i };
});

const subCategoryID = await SubCategory.find({
  $or: singleCategoryQuery,
});

console.log(subCategoryID);

for your promise, sorry I can't help.

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