如何在Parse Platform NodeJS中批量保存上万条数据
Parse Platform大批量数据插入失败问题解决
问题描述
我是Parse Platform的新手用户,尝试向Parse DB插入81000行数据,最开始编写的代码如下:
const uri = "/the.json" const res = await axios.get(uri) const dataresult = Object.keys(res.data) if (dataresult.length > 0) { res.data.forEach(function (datakp) { var kp = new Parse.Object("theClass"); kp.save(datakp) .then((res) => { console.log('oke ' + res.id) }), (error) => { console.log('err : '+ error.message) } }) }
运行后控制台无任何报错,但Parse DB中没有存入任何数据;但如果限制仅插入1000行数据,就可以正常存入数据库,对应代码如下:
if (dataresult.length > 0) { res.data.forEach(function (datakp, index) { if (index < 1000) { var kp = new Parse.Object("theClass"); kp.save(datakp) .then((res) => { console.log('oke ' + res.id) }), (error) => { console.log('err : '+ error.message) } } }) }
原因分析
- 初始代码在循环中逐个调用
save()方法,相当于一次性发起81000个并发请求,超出了Parse Server的并发阈值、请求频率限制,直接被服务端限流拦截,所以没有数据写入 - 1000行以内的请求量级在限流阈值范围内,所以可以正常写入
- 原有代码的promise错误回调语法存在错误,部分请求报错无法被正常捕获,所以看不到报错提示
解决方案
使用Parse官方提供的批量保存方法Parse.Object.saveAll(),该方法会自动将所有待保存对象合并为少量批量请求提交,不会触发并发限制,插入性能也远高于逐行提交。
最终完整实现代码如下:
const uri = "/the.json" const res = await axios.get(uri) const dataresult = Object.keys(res.data) const objs = []; const theKP = Parse.Object.extend("theClass") if (dataresult.length > 0) { res.data.forEach(function (datakp) { var thekp = new theKP() thekp.set(datakp) objs.push(thekp); }) } Parse.Object.saveAll(objs) .then((res) => { console.log('oke updated ' + dataresult.length) }), (error) => { console.log('err : '+ error.message) }
内容的提问来源于stack exchange,提问作者Yanwar Purnama
相关产品推荐
相关产品推荐

