javascript - 在 map 函数内从 Mongoose 获取文档会返回 Promise 待处理以及数据

标签 javascript node.js mongodb asynchronous mongoose

所以我有这个字符串数组,我将其用作过滤器以使用 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/

相关文章:

javascript - d3.js 中比例变化时图表不会变化

javascript - 如何通过 i18next 从临时翻译的组件中检索 ref

javascript - Node.js 应用程序的配置管理选项

node.js - 有没有办法在node.js中使用带有读取流的ffprobe(fluent-ffmpeg)输入?

javascript - 使用 Express mongo 显示类别

javascript - 如何获取数组中的value属性?

javascript - DOM 更改时向所有 INPUT 元素添加事件监听器

node.js - NodeJS VM2 设置为 'redirect' 时访问控制台的正确方法

javascript - meteor 无法访问收藏

angular - 如何修复排序、限制和跳过不适用于大量数据的问题