从Mongodb获取阵列。未处理的承诺拒绝

我正在努力使用一个函数,该函数旨在从Mongo数据库(在Node JS中)提取数组并返回它。尽管这个想法很简单,并且我已经多次编写了这种代码。我想念一些东西。

这是该函数的代码:

function getDBArray(reqID) {
  MongoClient.connect(databaseUri, {useUnifiedTopology: true}, function (err, client) {
    if (err) {
      console.log('getDBArray: Error = ' + err)
      throw err
    }

    const db = client.db()
    let srchQuery = {}
    srchQuery['fieldID'] = reqID
    db.collection('theList', async function (err, collection) {
      try {
        await collection.find(srchQuery, {'target': true}).toArray(function (err, items) {
          if (err) throw err

          const resultArray = items;
          client.close();

          return resultArray;
        })
      }
      catch (error) {
        console.log('-catch (getDBArray)- ::>> ' + error)
      }
    })
  });
} /* End of getDBArray */

这是调用代码:

let myArray = getDBArray(dataID)
myArray.forEach(element => {
  console.log('myArray:'+element)
});

这就是我不断获得的日志:

...+00:00 app[web.1]: (node:23) UnhandledPromiseRejectionWarning: TypeError: Cannot read property   'forEach' of undefined
...+00:00 app[web.1]: at .... (/app/server.js:55:21)
...+00:00 app[web.1]: at ....
......
...+00:00 app[web.1]: (node:23) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block,
or by rejecting a promise which was not handled with .catch(). 
To terminate the node process on unhandled promise rejection, use the CLI flag...
...+00:00 app[web.1]: (node:23) [DEP0018] DeprecationWarning: Unhandled promise rejections
are deprecated. In the future, promise rejections that are not handled will terminate
the Node.js process with a non-zero exit code.

任何人都可以看到我在功能中未正确执行操作以解决此问题吗?

评论