首页 > 解决方案 > Firebase Cloud FireStore:插入大型数组

问题描述

免责声明:我已经编程大约 4 个月了,所以我对编程还是很陌生。

我正在将 Firebase Cloud Firestore 用于数据库,并在其中插入包含大量数据的 CSV 文件。每个文件的长度约为 100k 条记录。我正在进行的项目需要用户从网页上传这些 CSV。

我创建了一个文件上传器,我正在使用 PapaParse JS 工具来解析 csv,它做得非常好,它会立即返回一个数组,即使它很长。我尝试使用我能找到的最大文件,然后将其记录到控制台,速度非常快。

问题是当我获取它给我的那个数组并循环遍历它并将它插入到 Cloud Firestore 中时。它有效,数据完全按照我想要的方式插入。但这很慢。如果我关闭浏览器窗口,它会停止插入。仅插入 50 条记录大约需要 10-15 秒。因此,对于 10 万条记录的文件,这是行不通的。

我正在考虑使用 Cloud Functions,但在我现在尝试了解所有这些工作原理之前,也许我只是没有以有效的方式这样做?所以我想在这里问。

这是JS

// Get the file uploader in the dom
var uploader = document.getElementById('vc-file-upload');

// Listen for when file is uploaded 
uploader.addEventListener('change',function(e){
		
		// Get the file 
		var file = e.target.files[0];

		// Parse the CSV File and insert into Firestore
		const csv = Papa.parse(file, {
			header: true,
			complete: function(results) {
				console.log(results);
				
				sim = results.data;
				var simLength = sim.length;
				for (var i = 0; i < simLength;i++) {
					var indSim = sim[i]
					iccid = indSim.iccid;
					const docRef = firestore.collection('vc_uploads').doc(iccid);
					docRef.set({indSim}).then(function() {
					console.log('Insert Complete.')
					}).catch(function (err) {
					console.log('Got an error: '+ err)
				 	})
				};

			}
		});
});

标签: javascriptfirebasegoogle-cloud-firestorepapaparse

解决方案


如果您只是上传文件(可能是到云存储)并在 Cloud Functions 或其他一些后端执行数据库操作,几乎可以肯定总体上会更快,即使用户离开应用程序也会完成。


推荐阅读