首页 > 解决方案 > Mongoose 和 Node.js 中的 bulkwrite 堆内存错误

问题描述

我正在为 bulkWrite 操作而苦苦挣扎。我正在处理 100,000 个数据。以下代码适用于 40k 数据。如果我尝试保存超过 50k 的数据,我会遇到内存问题。

我尝试了 insertMany(),它失败了 20k 数据。什么是 upsert 100,000 数据的有效方法?

代码:

async bulkInsertData(array) {
      const options = [];
      await sleep(60000);
      for (const item of array) {
        options.push({
          updateOne: {
            filter: { "id": item.id },
            update: {
              "$set": 
              {
                caseType : item.caseType,
                category : item.category
              }
            },
            upsert: true
          }
        })
      };
      await sleep(60000);
      const result = await this.dataModel.bulkWrite(options , { ordered: false })
      console.log(result)          
    }

错误

 <--- Last few GCs --->

[22:0x5f968d0]  1896003 ms: Mark-sweep 502.2 (519.2) -> 498.4 (518.9) MB, 435.5 / 0.0 ms  (average mu = 0.158, current mu = 0.051) allocation failure scavenge might not succeed

[22:0x5f968d0]  1896424 ms: Mark-sweep 502.4 (518.9) -> 498.7 (519.9) MB, 392.6 / 0.0 ms  (average mu = 0.117, current mu = 0.067) allocation failure scavenge might not succeed

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

标签: node.jsmongodbnestjsbulkinsert

解决方案


我认为这取决于你的情况。根据我的个人经验,我尝试了几种不同的方法。

  1. 只需通过设置来更新 NodeJS 使用内存大小--max-old-space-size=SIZE。您可以查阅文档https://nodejs.org/api/cli.html#--max-old-space-sizesize-in-megabytes。您可以尝试错误以找到合适的限制。
  2. 就像@devatherock 建议的那样,您应该尝试批量插入。
  3. 尝试使用 mongo-native 驱动程序(https://mongodb.github.io/node-mongodb-native/)而不是 mongoose。mongoose 是很好的 ORM 工具,但内存大小会更大。如果要插入大量数据,请尝试使用本机驱动程序并直接插入数据库。

推荐阅读