node.js - 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
解决方案
我认为这取决于你的情况。根据我的个人经验,我尝试了几种不同的方法。
- 只需通过设置来更新 NodeJS 使用内存大小
--max-old-space-size=SIZE
。您可以查阅文档https://nodejs.org/api/cli.html#--max-old-space-sizesize-in-megabytes。您可以尝试错误以找到合适的限制。 - 就像@devatherock 建议的那样,您应该尝试批量插入。
- 尝试使用 mongo-native 驱动程序(https://mongodb.github.io/node-mongodb-native/)而不是 mongoose。mongoose 是很好的 ORM 工具,但内存大小会更大。如果要插入大量数据,请尝试使用本机驱动程序并直接插入数据库。
推荐阅读
- assembly - 为什么 x86 只有一种形式的条件移动,而不是立即数或 8 位?
- c - 调用 open 时如何调用 sys_open 而不是 sys_openat
- python - 多语言 DjangoCMS
- python - 如何从 python 中的主列表创建两个 XORable 列表?
- python - 从项目目录导入包
- c++ - 我们可以在 O(1) 时间内反转一个堆栈吗
- javascript - 隐藏表格行有效,但淡出无效
- mysql - 连接表的spring删除行
- java - 线程“main”java.lang.Error 中的异常:未解决的编译问题:在 Datatypes.main(Datatypes.java:4)
- arduino - 我在将代码上传到我的 arduino nano 时遇到问题