【问题标题】:Iterating over array in a try…catch…finally results in "MongoError: Cannot use a session that has ended"在 try...catch... 中迭代数组最终导致“MongoError:无法使用已结束的会话”
【发布时间】:2020-12-11 23:05:29
【问题描述】:

我有一个函数可以连接到 Mongo 数据库,然后在数据库中查找与数组匹配的文档。

该函数实际上工作正常,并且我想要的数据正在由 checkIfExist() 找到并返回。然而,该函数在控制台中返回一个错误,尽管它工作。报错是“MongoError: Cannot use a session that has ending”,如下图。

我不明白我在这里做错了什么。

错误:

功能:

async function main() {
  const uri = 'URL';
  const client = new MongoClient(uri, { useUnifiedTopology: true });
  const pairData = [`_EURAUD_data`, `_EURCAD_data`, `_EURCHF_data`];
  await client.connect();
  const db = client.db('daily-ohlc').collection('ohlcs');

  try {
    const checkIfExist = async () => {
      pairData.map(pair => {
        const findstuff = db.find({ _id: pair._id }).toArray();
        console.log(`${findstuff}`);
      });
    };
    await checkIfExist();
  } catch (e) {
    console.error(e);
  } finally {
    console.log(`closing timne`);
    await client.close();
  }
}
main().catch(console.error);

我尝试过的事情。

  1. 我尝试将两秒的 setTimeout 添加到 await.client.close() 中,但没有收到错误消息。所以看起来客户端关闭得太快了。
  2. 替换 checkIfExist() 中的 .map,使其不会迭代并且可以正常工作。

【问题讨论】:

  • return pairData.map...你没有从 map 函数返回一个值,也不需要将你的 await 放在你的 try 块之外。然后,当您调用 main() 时,如果 promise 返回,则使用 then 记录 resolve 对象,然后如果 promise 被拒绝,您可以使用 catch 记录错误

标签: javascript node.js mongodb


【解决方案1】:

解决方案很简单,将 Array.map 包装在 Promise.all 方法中。当我这样做时,Array.map 在进入 finally 块之前完成。

async function main() {
  const uri = 'URL';
  const client = new MongoClient(uri, { useUnifiedTopology: true });

  try {
    await client.connect();
    const pairData = await cleanObject();
    const db = client.db('daily-ohlc').collection('ohlcs');
    const updateOrCreate = async () =>
      //needs to be in a promise
      Promise.all(
        pairData.map(async pair => {
          const check = db
            .find({ _id: pair._id, 'data.date': pair.data[0].date })
            .toArray()
            .then(value => value.length === 0);

          if (check) {
            return db
              .updateOne({ _id: pair._id, 'data.date': pair.data[0].date }, { $set: { 'data.$': pair.data[0] } }, { upsert: true })
              .then(result => `UPDATED DAY: ${pair._id}`)
              .catch(er => console.log(er));
          }
          return db
            .updateOne({ _id: pair._id }, { $push: { data: { $each: [pair.data[0]], $position: 0 } } }, { upsert: true })
            .then(result => `ADDED DAY: ${pair._id}`)
            .catch(er => console.log(er));
        })
      );
    console.log(await updateOrCreate());
    await updateOrCreate();
  } catch (e) {
    console.error(e);
  } finally {
    console.log(`sever connection closing...`);
    await client.close();
  }
}
main().catch(error => console.log(error));

【讨论】:

    猜你喜欢
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 2018-10-03
    • 2020-06-09
    相关资源
    最近更新 更多