【问题标题】:Passing a MongoDB collection to an array in NodeJS将 MongoDB 集合传递给 NodeJS 中的数组
【发布时间】:2020-03-17 13:49:12
【问题描述】:

我在从 MongoDB 集合中获取数据并将其返回到 NodeJS 代码中的数组时遇到问题。

到目前为止的代码返回了一个承诺,我不完全知道如何处理。

任何帮助将不胜感激。

async function loadData() {

    try {
        // Connect to the MongoDB cluster
        console.log('Attempting to connect to DB')
        client.connect(async err => {
            const collection = client.db("db").collection("collection");
            await collection.find({}).toArray().then((data) => {

            //Getting stumped as the data gets returned as a promise and does not get added to an array

            }
            );

        client.close();
        console.log('Closed DB connection');

        });
    } catch (e) {
    console.error(e);
    }

【问题讨论】:

    标签: arrays node.js mongodb promise


    【解决方案1】:

    你使用了错误的承诺以及asyncawait。 async/await 的目的是避免使用.then 函数。选择一个,使用或。

    使用回调方法:

    collection.find({}).toArray().then((data) => {
      console.log(data);
    }, err => {
      // this gets called if there is an error only
      console.log(err);
    });
    

    或使用异步/等待:

    try {
      const data = await collection.find({}).toArray();
    }
    catch(err) {
      console.log(err);
    }
    

    请注意,如果您选择使用 async/await,则包含函数必须标记为 async,您已经在这样做了。如果使用上述回调方法,则不需要。

    【讨论】:

      【解决方案2】:
      Don't execute the Promise inside the loadData function 
      
      
       function loadData() {
      
          try {
              // Connect to the MongoDB cluster
              console.log('Attempting to connect to DB')
              client.connect(async err => {
                  const collection = client.db("db").collection("collection");
                  return collection.find({})
                  );
      
              client.close();
              console.log('Closed DB connection');
      
              });
          } catch (e) {
          console.error(e);
          }
      

      并拨打电话获取您的数据

      try {
        const your_Array = await loadData().toArray();
      }
      catch(err) {
        console.log(err);
      }
      

      对于 MongoDB 连接,我认为您做错了,请关注此gist

      【讨论】:

      • 谢谢! :) 但是,我必须注意我没有使用猫鼬。相反,我使用的是官方的 MongoDB 连接器
      • 使用 ORM 将为您提供比官方连接器更多的功能!
      猜你喜欢
      • 2021-07-12
      • 2017-12-04
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 2016-09-24
      • 2021-02-25
      • 2020-12-24
      相关资源
      最近更新 更多