所以我有这个字符串数组,我将其用作过滤器以使用 Mongoose 从 MongoDB 获取文档。我成功从数据库取回数据,但它也返回 Promise { <pending> }
在控制台上,即使我用 Promise.all
包装 map 函数.
请注意,此映射函数嵌套在两层深度 for in
中为了简单起见,我省略了循环。
假设这是字符串数组:
const subCategories = [ 'Politics', 'Entertainment' ];
这是 map 功能:
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 );
promise 让我头晕。在过去的 1-2 年里,我尝试学习 Promise 超过 5-6 次,但它仍然让我感到困惑。因此,如果可以的话,请提供 Async/Await 的解决方案。
最佳答案
如果您只对结果感兴趣,请尝试以下方法:
const subCategories = [ 'Politics', 'Entertainment' ];
const queries = subCategories.map((i) => {
return { subCategory: i };
});
const subCategoryID = await SubCategory.find({
$or: queries,
});
console.log(subCategoryID);
使用 $or
mongodb手册中对运算符进行了解释:
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>
.
更多关于它here .
在 mongoose 中,你可以在任何 find
中使用它方法。
请解释一下你的 promise ,抱歉我帮不上忙。
如果这解决了您的问题,请标记为已回答。
关于javascript - 在 map 函数内从 Mongoose 获取文档会返回 Promise 待处理以及数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69780763/