让我们拿这个样本
export let index = (req: Request, res: Response) => {
for (let i = 0; i < 10; i++) {
let bulk = Faker.collection.initializeUnorderedBulkOp();
for (let y = 0; y < 200000; y++) {
bulk.insert({
name: randomName(),
nights: Math.random(),
price: Math.random(),
type1: Math.random(),
type2: Math.random(),
type3: Math.random(),
type4: Math.random(),
departure: mongoose.Types.ObjectId(randomAreaID()),
destination: mongoose.Types.ObjectId(randomAreaID()),
refundable: randomBool(),
active: randomBool(),
date_start: randomDate(),
date_end: randomDate(),
});
}
bulk.execute();
}
return res.json({data: true});
};
使用此代码,我尝试在我的收藏中插入“some”文档。
我使用initializeUnorderedBulkOp但是如果我尝试保存超过100万个文档,那么我就会遇到内存问题
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
我知道我可以增加内存,但我想找到更好的解决方案。因为现在我需要2米的记录,但将来我需要100米。
有任何避免记忆问题的建议吗?
答案 0 :(得分:0)
Async / Await是解决方案。没有堆内存不足的200.000.000文件。无限制现在是限制....
let bulkPromise = (data) => {
return new Promise((resolve, reject) => {
if (data.length > 0) {
let bulk = Faker.collection.initializeUnorderedBulkOp();
data.forEach((d) => {
bulk.insert(d);
})
bulk.execute(() => {
resolve(true);
});
} else {
resolve(false);
}
});
}
export let index = async (req: Request, res: Response) => {
for (let i = 0; i < 100; i++) {
let data = [];
for (let y = 0; y < 200000; y++) {
data.push({
name: randomName(),
nights: Math.random(),
price: Math.random(),
type1: Math.random(),
type2: Math.random(),
type3: Math.random(),
type4: Math.random(),
departure: mongoose.Types.ObjectId(randomAreaID()),
destination: mongoose.Types.ObjectId(randomAreaID()),
refundable: randomBool(),
active: randomBool(),
date_start: randomDate(),
date_end: randomDate(),
});
}
await bulkPromise(data).then((data) => {
console.log(i);
});
}
return res.json({data: true});
};