首页 > 解决方案 > MongoDB Aggregation+Cursor 加上 JS Generators

问题描述

这是我第一次在 JavaScript (Node.js) 中使用生成器。我只是希望有人验证实现是否正确。如果没有,请提出更好的方法。

所以,这里有两个问题:

  1. 是否优化了基于生成器的实现。并且在优化之前,是否正确。(但是,我得到了结果,只是想从阻塞/非阻塞的角度来理解它)。
  2. 我正在使用 node-fetch 进行 10 次 API 调用并在数组中收集 Promise。如果我需要在 AWS Lambda 上部署它,如果我不使用 Promise.all(array) 并且无论 API 调用是否成功都简单地返回,是否可以?反正我不在乎反应。我只是触发 API。

要求:

  1. 在 AWS Lambda 上托管一个使用 Mongoose 驱动程序与 MongoDB 对话的 Node.js 函数。
  2. 从 MongoDB 中获取 10000 个文档。
  3. 这些文档具有以下架构。_id 键保存一个长度为 163 的字符串值:
{
 _id: "cSKhwtczH4QV7zM-43wKH:APA91bF678GW3-EEe8YGt3l1kbSpGJ286IIY2VjImfCL036rPugMkudEUPbtcQsC"
}
  1. 我对 _ids 的值感兴趣,我一次只能处理 1000 个 _ids。
  2. 将它们放入一个数组并进行 API 调用。因此,对于 10000 个 _id,我需要使用其中的 10 个数组进行 10 次 API 调用。

我使用 Node.js 生成器进行的实现:

async function* generatorFunction() {
    await connectMongo();
    const cursor = Model.aggregate([
        //... some pipeline here
    ]).cursor();
    const GROUP_LIMIT = 1000;
    let newGroup = [];
    for await (const doc of cursor) {
        if (newGroup.length == GROUP_LIMIT) {
            yield newGroup;
            newGroup = [];
        }
        newGroup.push(doc._id);
    }
    yield newGroup;
    await disconnectMongo();
}

const gen = generatorFunction();

(async () => {
    const promises = [];
    for await (const newGroup of gen) {
        // POST request using node-fetch
        // Ignore the syntax
        promises.push(fetch('API', { body: { newGroup } }));
    }
    // Do I need to do this?
    // Or can this be skipped?
    // I do not care about the response anyway...
    // I just need to trigger the API and forget...
    await Promise.all(promises);
    return {
        success: true,
    };
})();

标签: javascriptnode.jsmongodbaws-lambdaasync-await

解决方案


推荐阅读