javascript - 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 似乎不想工作!
解决方案
您当前的函数不起作用,因为它会同步返回并稍后修改数组。
将您的函数更改为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
}))
推荐阅读
- android - 找不到 LocalApplicationData 的存储文件夹
- python - python中的try/except语句
- php - 如何在 PHP GD 中编辑 2 个帖子的文本颜色
- javascript - Javascript:函数范围的对象
- angular - Angular 6中的条形图
- .net - MVC 连接表显示
- c# - Xamarin Forms ListView 滚动位置 - MVVM
- nwjs - 在 NW.js 构建中分发 node_modules 文件夹的最佳方式?
- .net - 不显示动态添加的控件
- windows-subsystem-for-linux - wsl ubuntu .bashrc 停止运行