首页 > 解决方案 > MongoDB函数未正确返回数组

问题描述

我试图以一种简单有效的方式找出数组中的每个字符串是否存在于 MongoDB 上。要搜索的字段是已知的(即名称)

我遇到的问题是,当调用下面的函数时,它返回未定义。

const generateNaughtyList = (listtoCheck: Array<string>): Array<string> => {
  let doesntExist = []
  listtoCheck.forEach(async (e) => {
    const docCount = await Article.countDocuments({ name: e }).exec();
    if (docCount != 1) doesntExist.push(e)
  })
  return doesntExist
}

调用函数

  const hello = await generateNaughtyList(Stringlist)
  console.log(hello)

如果我在循环期间尝试 console.log out (ie)


 if (docCount != 1) console.log('It doesn't exist')

它工作正常吗?

如果我使用另一种循环方法

  for (let i = 0; i <= listtoCheck.length-1; i++) {
    const docCount: number = await Article.countDocuments({ name: listtoCheck[i] }).exec();
    if (docCount != 1) doesntExist.push(listtoCheck[i])
  }

它工作正常。forEach 似乎不想工作!

标签: javascriptnode.jsmongodb

解决方案


您当前的函数不起作用,因为它会同步返回并稍后修改数组。

将您的函数更改为async函数,以便在检查所有字符串后解析。

在下面修改后的函数中,我还Promise.all()结合使用 to Array.map()(instaed of forEach) 来获取结果数组。

const generateNaughtyList = async (listtoCheck: Array<string>): Array<string> => 
  await Promise.all(listtoCheck.map(async (e) => {
    const docCount = await Article.countDocuments({ name: e }).exec();
    if (docCount != 1) return e
  }))

推荐阅读